反射以获取类中类属性的值



我有两种类型的类。

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() ?? "";

这是我想要实现的,但我不能用这种方式编码,因为出现错误。**

现在我想通过Reflection动态获取Info类内部Address类中addressInfo的值。我怎样才能做到这一点?谢谢

您可以尝试

var info = new Info();
var property = info
.GetType()
.GetProperty("address");
string val = (string)property
.PropertyType
.GetProperty("addressInfo")
.GetValue(property.GetValue(info));

注意:这缺乏合适的错误检查和容错能力,添加胡椒和盐调味

最新更新