繁体   English   中英

如何通过反射获取内部属性值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM