您可以使用Type.GetProperties 获取类型的属性,使用Type.IsAssignableFrom 查找是否可以将属性分配给ICurrency 变量。您可以使用 LINQ 查询检索所有匹配的属性:
var currencyProps=typeof(Rootobject).GetProperties()
.Where(pi=>typeof(ICurrency).IsAssignableFrom(pi.PropertyType))
.ToArray();
或
var currencyProps=( from pi in typeof(Rootobject).GetProperties()
where typeof(ICurrency).IsAssignableFrom(pi.PropertyType)
).ToArray();
您可以将currencyProps 数组缓存在静态字段中,并将其用于任何对象:
static PropertyInfo[] _currencyProps;
static void InitializeCurrencyProps()
{
var currencyProps=( from pi in typeof(RootObject).GetProperties()
where typeof(ICurrency).IsAssignableFrom(pi.PropertyType)
select pi);
_currencyProps=currencyProps.ToArray();
}
一旦你拥有了所有你想要的 PropertyInfo 对象,你就可以使用PropertyInfo.GetValue 从一个特定的实例中读取一个属性值,例如:
_currencyProps[0].GetValue(rootObject);
要查找所有具有值的属性,即不是 noll,您可以使用另一个查询:
var values=_currencyProps.Select(pi=>new {pi.Name,Value=pi.GetValue(rootobject)})
.Where(val=>val.Value!=null)
.ToArray();
或
var values = ( from pi in _currencyProps
let value=pi.GetValue(rootobject)
where value !=null
select new {pi.Name,value}
).ToArray();
您可以使用ToDictionary() 创建字典而不是数组:
var values = ( from pi in _currencyProps
let value=pi.GetValue(rootobject)
where value !=null
select new {pi.Name,Value=value}
).ToDictionary(pair=>pair.Name,pair=>pair.Value);
var usd=values["USD"];