繁体   English   中英

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

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

如何通过反射获取一些参数(或属性,如果被称为)?

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

GetValue返回object

您需要先投射它,然后再呼叫其他成员。

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;
    }
}

否则,您将只能使用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