获取泛型类型参数的实例的属性值

时间:2012-09-05 01:44:40

标签: c# generics reflection

使用反射:

如果我有X<Y>类型的实例(我不知道究竟是什么Y),因为X是泛型类型(X<T>),怎么做我在Y上获得了一个属性的值?

类似的东西:

Type yType = currentObject.GetType().GetGenericArguments()[0];

// How do I get yInstance???
var yInstance = Convert.ChangeType(???, yType);

我需要:

object requiredValue = yType.GetProperty("YProperty").GetValue(yInstance, null);

1 个答案:

答案 0 :(得分:2)

使用以下方法获取通用参数的PropertyInfo对象:

PropertyInfo myProperty = myGenericType.GetType().GenericTypeArguments[0].GetProperty("myPropertyName");

其中“0”是类定义中泛型类型的索引,“myPropertyName”是属性的名称。之后,像使用任何其他PropertyInfo对象一样使用它,例如:

myProperty.GetValue(obj); // Where obj is an instance of the generic type

[编辑:以下原始答案]

如果Y必须具有属性,则将类型T约束为必须实现包含该属性的接口的类型。例如:

public class MyGenericClass<Y> where Y:IMyInterface

然后将通用对象转换为接口并调用属性。