【发布时间】:2012-12-17 06:07:35
【问题描述】:
我有一个泛型类和一个对象值,其中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
【问题讨论】:
-
你在 typeof(Foo) 上调用 GetProperty() 吗?
-
GetProperty应该没问题。请发布一个简短但完整的程序来演示该问题。如果您使用的是 .NET 4,dynamic也可以很好地工作。 -
@JonSkeet 抱歉,我使用的是 3.5。上面的示例代码。
-
@gunr2171:您的示例无法编译,并且在应用了明显的修复后,
GetProperty不 返回 null。请展示一个简短但完整的程序确实实际演示了问题。
标签: c#