简体   繁体   English

反思-如何获得财产的属性?

[英]Reflection - How to get attribute of property?

How can i get some parameters (or attributes, if they are called so), with reflection? 如何通过反射获取一些参数(或属性,如果被称为)?

MyObject x = new MyObject(...);
..........
var propInfo = x.GetType().GetProperty("something");
if (propInfo != null) {
    xyz= propInfo.GetValue(x,null).Metrics.Width //<------ gives error
}

GetValue returns object . GetValue返回object

You need to cast it before calling other members. 您需要先投射它,然后再呼叫其他成员。

MyObject x = new MyObject(...);
//..........
var propInfo = x.GetType().GetProperty("something");
if (propInfo != null) {
    MyPropertyType xyz = (MyPropertyType)propInfo.GetValue(x,null);
    if(xyz != null) {
        double width = xyz.Metrics.Width;
    }
}

Otherwise you would be left with using dynamic object. 否则,您将只能使用dynamic对象。

MyObject x = new MyObject(...);
//..........
var propInfo = x.GetType().GetProperty("something");
if (propInfo != null) {
    dynamic xyz = propInfo.GetValue(x,null);
    if(xyz != null) {
        double width = xyz.Metrics.Width;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM