Work on object of type GenericType<T> regardless of T
In case two classes are of the same GenericType<> regardless of T I would like to do some stuff. Is this possible?
// class is given; I can't change it!!
public class MyGeneric<T> : MyBaseClass where T : struct, IComp开发者_运维技巧arable, IConvertible
{
public T MyProperty { get; set; }
}
public void DoStuff(MyBaseClass objA, MyBaseClass objB)
{
...
if (objA.GetType().IsGenericType && objA.GetGenericTypeDefinition() == typeof(MyGeneric<>) &&
objA.GetType() == objB.GetType())
{
//here I know that my objects do have a "MyProperty"
//I would like to do something like:
if (((MyGeneric<T>)objA).MyProperty.CompareTo(((MyGeneric<T>)objB).MyProperty) > 0) //doesn't work!!!!
{
//do stuff
}
}
}
It can be made to work if you change the DoStuff
method signature to
public void DoStuff<T>(MyBaseClass objA, MyBaseClass objB)
where T : struct, IComparable, IConvertible
{
// ...
}
However, you would have to know the type of T
at compile time in order to call the method; I 'm not sure if this would solve your problem.
Apart from that, the other solution is to use reflection:
var valueA = (IComparable)objA.GetType().GetProperty("MyProperty").GetValue(objA, null);
var valueB = (IComparable)objB.GetType().GetProperty("MyProperty").GetValue(objB, null);
if (valueA.CompareTo(valueB) > 0) {
// ...
}
This really doesn't make any sense:
objA.GetType() == objB.GetType()
ensures, that they are of the same type, i.e. not independent fromT
- If point 1 would be solved by simply removing this check, it still would make no sense to compare these properties, because the only thing that is the same in both instances is the name of the property. The type might be different. What should be the result of that?
If you really want to compare the properties, only if T is the same for both instances, just use this method:
public void DoStuff<T>(MyGeneric<T> objA, MyGeneric<T> objB)
where T : struct, IComparable, IConvertible
{
if (objA.MyProperty.CompareTo(objB.MyProperty) > 0)
{
//do stuff
}
}
If you don't know T
at compile time, you can use reflection as Jon suggests or you can use the new dynamic
keyword if you are using .NET 4:
public void DoStuff(MyBaseClass objA, MyBaseClass objB)
{
if (objA.GetType().IsGenericType &&
objA.GetGenericTypeDefinition() == typeof(MyGeneric<>) &&
objA.GetType() == objB.GetType()
)
{
dynamic objADyn = objA;
dynamic objBDyn = objB;
if (objADyn.MyProperty.CompareTo(objBDyn.MyProperty) > 0)
{
//do stuff
}
}
}
精彩评论