簡體   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