C#: Interface with Either Number or DateTime
My problem can be simplified to a List<> with X and Y coordinates that I'd like to group into an interface or abstract class. I then have a bunch of other functions that take this abstract class as an argument. The caveat to this is that the X element is either of a numerical or is a DateTime. Here's some sample code to illustrate what I'm trying to do:
//C# 4.0
abstract class Element : Group<DateTime, double>
{
public DateTime X {get; set;}
public double Y {get; set;}
}
public interface Group<T, U>
{
public T X {get; set;}
public U Y {get; set;}
}
void OtherObject.Do(List<Group<DateTime, double>> elm)
{
double[] X = 0;
for (int i = 0; i < elm.Count; i++)
{
if (elm[i].GetType() == typeof(DateTime))
{
X[i] = ((DateTime)elm[i].X).TOADate();
{
else
{
X[i] = elm.X;
}
}
//Other stuff
}
static Main()
{
List<Element> list = FactoryCreate();
OtherObject obj = new OtherObject();
obj.Do(list);
}
I'd like to be able to specify the List<Group<Dat开发者_开发百科eTime, double>>
argument to Do()
without specifying that the generic types. I'd just like to be able to do Do(List<Group> lst)
.
I could just eliminate the generic type parameters and use the dynamic data type in Group but I don't feel like thats the best way.
Is there an established pattern to deal with this issue? I'm 100% open to suggestions as to the correct way to model this data structure/class.
You can make a non-Generic IGroup
interface with object
properties and implement it explicitly.
I think you overcomplicated it. Your DateTime and double both do the same = they store date and time, so go and use one of them and convert values from the other type when needed. Or create your own class DateTimeOrDouble and put it in place of generic parameter. You cannot use generic parameters when you need date or double and need to call ToOADate(). In short: Don't use generic parameters at all, because you don't need it.
One more point: You are mixing here public interface and internal implementation. This is a wrong software design. Your interface should just define operations to access your data, and those operations should be independent of internal data representation. Then you should define some classes implemening this interface, i.e. one with DateTime and other one with double as the real data store. None of this needs to use generics.
精彩评论