最好的方式得到使用的getProperty子特性 [英] Best way to get sub properties using GetProperty
问题描述
公共类地址
{
公共字符串邮编{搞定;设置;}
}
公共类客户
{
公共地址地址{搞定;设置;}
}
我如何访问eitther邮编或Address.ZipCode 与反思?例如:
typeof运算(客户).GetProperty(邮编)?
您会需要这样的:
的PropertyInfo addressProperty = typeof运算(客户).GetProperty(地址);
ProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty(邮编);
对象地址= addressProperty.GetValue(客户,NULL);
对象邮政编码= zipCodeProperty.GetValue(地址,NULL);
基本上,如果你想采取一个字符串Address.ZipCode并导航下来,你需要通过拆分它。然后在每一步调用上的getProperty适当的类型,以获得财产本身,然后PropertyInfo.GetValue拿到链的下一个值。事情是这样的:
公共静态对象FollowPropertyPath(对象的值,字符串路径)
{
型currentType = value.GetType();
的foreach(在path.Split字符串propertyName的()'。')
{
的PropertyInfo财产= currentType.GetProperty(propertyName的);
值= property.GetValue(值null);
currentType = property.PropertyType;
}
返回值;
}
这样称呼它:
对象邮政编码= FollowPropertyPath(客户Address.ZipCode);
请注意,这个工作在编译时类型的属性。如果你想让它应付执行时间类型(例如:如果customer.Address没有一个ZipCode属性,而是由地址返回没有实际的类型),然后更改 property.PropertyType
到 property.GetType()
另外请注意,这没有任何错误处理等: )
public class Address
{
public string ZipCode {get; set;}
}
public class Customer
{
public Address Address {get; set;}
}
how can I access eitther "ZipCode" or "Address.ZipCode" with reflection? For example:
Typeof(Customer).GetProperty("ZipCode")?
You'd need something like:
PropertyInfo addressProperty = typeof(Customer).GetProperty("Address");
ProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty("ZipCode");
object address = addressProperty.GetValue(customer, null);
object zipCode = zipCodeProperty.GetValue(address, null);
Basically if you want to take a string "Address.ZipCode" and navigate down it, you need to split it by "." and then call GetProperty on the appropriate type at every step to get the property itself, then PropertyInfo.GetValue to get the next value in the chain. Something like this:
public static object FollowPropertyPath(object value, string path)
{
Type currentType = value.GetType();
foreach (string propertyName in path.Split('.'))
{
PropertyInfo property = currentType.GetProperty(propertyName);
value = property.GetValue(value, null);
currentType = property.PropertyType;
}
return value;
}
Call it like this:
object zipCode = FollowPropertyPath(customer, "Address.ZipCode");
Note that this works on the compile-time types of the properties. If you want it to cope with the execution time type (e.g. if customer.Address didn't have a ZipCode property, but the actual type returned by Address did) then change property.PropertyType
to property.GetType()
.
Also note that this doesn't have any error handling etc :)
这篇关于最好的方式得到使用的getProperty子特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!