【发布时间】:2019-11-01 14:26:59
【问题描述】:
我想使用反射从类对象中获取值。在这种情况下,Rating 是我的主类,它包含 Contribution 类的属性。
以下是我的班级结构
public class Rating
{
public string personal_client_id { get; set; }
public string risk_benefit_id { get; set; }
public string type { get; set; }
public string risk_event { get; set; }
public string value { get; set; }
public Contribution contribution { get; set; }
}
public class Contribution
{
public string from { get; set; }
public string value { get; set; }
}
现在我想要来自 contribution 属性的值,如下所示。
var Rating = RatingObject.Where(x => x.personal_client_id == pcid).FirstOrDefault();
if (Rating != null)
{
Type type = Rating.GetType();
PropertyInfo propertyInfo = type.GetProperty("contribution");
var aa = propertyInfo.GetValue(Rating, null);
//aa has the Contribution property now but i don't know how can i get the property value from
this object
//Remember i dont want to do this **((Contribution)(aa)).from**
}
else
{
return "";
}
请帮忙!
【问题讨论】:
-
GetValue 是正确的方法,但它返回对象,因此您需要强制转换
标签: c# .net reflection .net-core