在课堂上获得课堂财产价值的反思

时间:2020-09-09 06:06:17

标签: c# class reflection properties

我有2种课程。

public class Info
{
 public string name {get; set;}
 public Address address {get; set;}
}

public class Address
{
 public string addressInfo {get;set;}
 public string country {get;set;}
}

**

编辑:

Info info = new Info();
string subClass="address"; 
Type subType = info .GetType().GetProperty(subClass).PropertyType;
string val = typeof(subType).GetType().GetProperty("addressInfo").GetValue(data, null)?.ToString() ?? "";

这是我想要实现的,但是我不能以这种方式进行编码,导致它 出错了。 **

现在,我想通过反射动态获取Info类内部的Address类中的addressInfo的值。我该如何实现? 谢谢!!!

1 个答案:

答案 0 :(得分:1)

您可以尝试

var info = new Info();

var property = info
   .GetType()
   .GetProperty("address");

string val = (string)property
   .PropertyType
   .GetProperty("addressInfo")
   .GetValue(property.GetValue(info));

注意:此方法缺乏适当的错误检查和容错功能,请添加胡椒粉和盐调味

相关问题