我有一个泛型类,一个对象值在哪里obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>).
class Foo<T>
{
public List<T> Items { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我如何获得的值Items从obj?记住,obj是一个Object,我不能演员obj,Foo因为我不知道是什么T.
我希望为此使用反射,但每次我这样做GetProperty("Items")都会返回null.但是,如果有人知道一个好的方法,无需反思就可以做到这一点.
假设我的代码如下所示:
//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 …Run Code Online (Sandbox Code Playgroud) c# ×1