我有一个通用类,以及一个对象值,其中 obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>)
。
class Foo<T>
{
public List<T> Items { get; set; }
}
我如何从`obj`获取`Items`的值?请记住,`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 itemValue = propInfo.GetValue(obj, null); //and this breaks because it's null
dynamic
也可以很好地工作。GetProperty
应该没问题。请发布一个简短但完整的程序来演示问题。 - Jon SkeetGetProperty
不会 返回 null。请展示一个简短但完整的程序,确实 演示了这个问题。 - Jon Skeet