我正在尝试通过反射来获取类的属性类型,但是它返回我唯一的RuntimePropertyInfo-作为类型的名称。

我有对象MyObjectactualData-它包含属性-作为字符串的“名称”和作为类型DatumType的“Item”

当我调试时,我看到,actualData具有2个属性,第一个是字符串类型,第二个是DatumType,但是当我使用此属性时:
string typeName = actualData.getType().getProperty("Item").getType().Name-它返回我RuntimePropertyInfo,而不是DatumType

可以看到我在做什么错吗?我正在使用C#-.Net 4.0。
非常感谢!

最佳答案

您正在获取PropertyInfo对象getProperty()返回的类型。尝试

string typeName = actualData.getType().getProperty("Item").PropertyType.Name;

如果要通过PropertyInfo对象分配当前分配给该对象的值的类型,可以调用:
string typeName = actualData.getType().getProperty("Item").GetValue(actualData, null).GetType().Name;

但是在这种情况下,您也可以简单地调用:
string typeName = actualData.Item.GetType().Name;

09-18 17:44