获取通用类的属性 [英] Get property of generic class
问题描述
我有一个通用类,还有一个对象值,其中 obj.GetType()。GetGenericTypeDefinition()== typeof(Foo<>)
。
I have a generic class, and an object value where obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>)
.
class Foo<T>
{
public List<T> Items { get; set; }
}
如何获取 Items <的值/ code>来自
obj
?记住, obj
是一个 Object
,我不能转换 obj
为 Foo
,因为我不知道 T
是什么。
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.
我希望对此使用反射,但是每次我执行 GetProperty( Items)
时,它都会返回null。但是,如果有人知道一种无需反思的好方法,就一定可以。
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
推荐答案
可以使用:
Type t = obj.GetType();
PropertyInfo prop = t.GetProperty("Items");
object list = prop.GetValue(obj);
您将无法转换为 List< T> 当然,由于您不知道类型
T
,所以直接使用code>,但是您仍然应该能够获得的值项目
。
You will not be able to cast as a List<T>
directly, of course, as you don't know the type T
, but you should still be able to get the value of Items
.
编辑:
下面是一个完整的示例,以演示此工作:
The following is a complete example, to demonstrate this working:
// Define other methods and classes here
class Foo<T>
{
public List<T> Items { get; set; }
}
class Program
{
void Main()
{
//just to demonstrate where this comes from
Foo<int> fooObject = new Foo<int>();
fooObject.Items = new List<int> { 1, 2, 3};
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);
Console.WriteLine(itemValue);
// Does not print out NULL - prints out System.Collections.Generic.List`1[System.Int32]
IList values = (IList)itemValue;
foreach(var val in values)
Console.WriteLine(val); // Writes out values appropriately
}
}
这篇关于获取通用类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!