如何使用反射获取一些参数(或属性,如果这样调用的话)?
MyObject x = new MyObject(...);
..........
var propInfo = x.GetType().GetProperty("something");
if (propInfo != null) {
xyz= propInfo.GetValue(x,null).Metrics.Width //<------ gives error
}发布于 2017-09-29 05:47:09
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;
}
}https://stackoverflow.com/questions/46478705
复制相似问题