[英]How get inner property value by reflection
我想使用反射從 class object 中獲取值。 在這種情況下,Rating 是我的主要 class ,其中包含貢獻 class 的屬性。
以下是我的 class 的結構
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; }
}
現在我想要來自貢獻屬性的值,如下所示。
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 "";
}
請幫忙!
鑒於您已經擁有 object rating
,您可以為要從Contribuition
類型讀取的屬性定義一個PropertyInfo
,並使用rating.contribution
上的引用來讀取它。 樣品
PropertyInfo propertyInfo = typeof(Rating).GetProperty("contribution");
var contribution = propertyInfo.GetValue(rating, null) as Contribution;
if (contribution != null)
{
Console.WriteLine(contribution.from);
Console.WriteLine(contribution.value);
}
請記住, PropertyInfo.GetValue
方法從object
類型返回一個東西,因此,您必須將其轉換為預期的類型。
您可以強制 aa 的類型為動態類型,而不是使用 var。
dynamic aa = propertyInfo.GetValue(Rating, null);
return aa.from;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.