【问题标题】:How get inner property value by reflection如何通过反射获取内部属性值
【发布时间】: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


【解决方案1】:

假设您已经拥有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 类型返回一个东西,所以,你必须将它转换为预期的类型。

【讨论】:

  • typeof(Contribution).GetProperty("from");.我不想硬编码属性名称好友.. 像贡献一样。而不是我想要类似 var aa = propertyInfo.GetValue(Rating, null);... 我想使用这个 aa 对象的类型,它已经是类型贡献...我希望你明白
  • 查看我的更新。不确定我是否明白,但您可以使用asGetValue 的结果安全地转换为贡献,并检查它是否不为空并使用该对象。
【解决方案2】:

您可以强制 aa 的类型为动态类型,而不是使用 var。

dynamic aa = propertyInfo.GetValue(Rating, null);
return aa.from;

【讨论】:

    猜你喜欢
    • 2013-07-18
    • 2023-03-28
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多