获取泛型类型参数实例的属性值 [英] Get property value of instance of generic type's argument

查看:739
本文介绍了获取泛型类型参数实例的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用反射:

如果我有一个类型为 X 的实例(我不因为 X 是一个泛型类型( X ),所以 / code>),如何获得 Y



的属性值:

 类型yType = currentObject.GetType()。GetGenericArguments()[0]; 

//如何获得yInstance?
var yInstance = Convert.ChangeType(???,yType);

我需要:

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


解决方案

使用以下命令获取泛型参数的PropertyInfo对象: / p>

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

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

  myProperty.GetValue(obj); //其中obj是泛型类型的一个实例



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

  public class MyGenericClass< Y>其中Y:IMyInterface 

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


Using reflection:

If I have an instance of type X<Y> (I don't know what Y is exactly) since X is a generic type (X<T>), how do I get the value of a property on Y?

Something like:

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

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

I need to get to:

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

解决方案

Get the PropertyInfo object for the generic argument using:

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

where "0" is the index of the generic type in the class definition and "myPropertyName" is the name of the property. After that, use it as you would any other PropertyInfo object, for example:

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

[Edit: original answer below]

If Y must have a property, constrain the type T to one that must implement an interface that contains that property. For example:

public class MyGenericClass<Y> where Y:IMyInterface

Then cast the generic object to the interface and call the property.

这篇关于获取泛型类型参数实例的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆