I have a generic class, and an object value where obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>)
.
class Foo<T>
{
public List<T> Items { get; set; }
}
How do I get the value of Items
from obj
? Remember, obj
is an Object
, I can't cast obj
as Foo
because I don't know what T
is.
I was hoping to use reflection for this, but each time I do GetProperty("Items")
it returns null. However, if someone knows a good way to do this without reflection, by all means.
Let's say my code looks like this:
//just to demonstrate where this comes from
Foo<int> fooObject = new Foo<int>();
fooObject.Items = someList;
object obj = (object)fooObject;
//now trying to get the Item value back from obj
//assume I have no idea what <T> is
PropertyInfo propInfo = obj.GetType().GetProperty("Items"); //this returns null
object itemValue = propInfo.GetValue(obj, null); //and this breaks because it's null
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…