反射以获取 class 属性 在 class 中的值
Reflection to get value of class property in class
我有 2 种 class。
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;}
}
**
Edit:
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() ?? "";
This is what I want to achieve but I cannot code in this way, cause it
got error.
**
现在我想通过Reflection 动态获取Address class 里面Info class 里面的addressInfo 的值。我怎样才能做到这一点?
谢谢!!!
你可以试试
var info = new Info();
var property = info
.GetType()
.GetProperty("address");
string val = (string)property
.PropertyType
.GetProperty("addressInfo")
.GetValue(property.GetValue(info));
注意 : 这个是缺少合适的错误校验和容错,酌情加盐
我有 2 种 class。
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;}
}
**
Edit:
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() ?? "";
This is what I want to achieve but I cannot code in this way, cause it got error. **
现在我想通过Reflection 动态获取Address class 里面Info class 里面的addressInfo 的值。我怎样才能做到这一点? 谢谢!!!
你可以试试
var info = new Info();
var property = info
.GetType()
.GetProperty("address");
string val = (string)property
.PropertyType
.GetProperty("addressInfo")
.GetValue(property.GetValue(info));
注意 : 这个是缺少合适的错误校验和容错,酌情加盐