Alrighty, so I use generics in my project and sometimes I want to run through all the properties of a class and determine their type. Or, rather, I want to know if a given property is an X or derives from an X.
So I use the following line (with an example class):
if (typeof(GenericDataObjectWithUniqueID).IsAssignableFrom(props[i].PropertyType))
Here, if the property is, or derives from, the class GenericDataObjectWithUniqueID , it will pass the if condition.
But in the case of a generic class, I just can't do that.
My generic class is very simple, just this:
public class GenericPrimitiveContainer<T>
{
private T _value;
public T Value
{
get
{
return _value;
}
set
{
_value = value;
}
}
}
The class, the properties of which I want to loop through, contains such a generic class, like this:
public GenericPrimitiveContainer<int> IContainer
But if we go back to the above line and substitute, this doesn't work:
if (typeof(GenericPrimitiveContainer).IsAssignableFrom(props[i].PropertyType))
In fact it gives a compile error.
So I tried this:
if (typeof(GenericPrimitiveContainer<>).IsAssignableFrom(props[i].PropertyType))
It compiles, but doesn't catch the property in question.
I can also use this:
if (typeof(GenericPrimitiveContainer<int>).IsAssignableFrom(props[i].PropertyType))
This works, but it's obviously not at all generic.
If possible, what I want to do is get what type it is, then get what the generic type is (int in this case), and then later instantiate the class and assign data to it based on the generic type.
Can anyone help?
Aucun commentaire:
Enregistrer un commentaire