有没有什么方法可以只选择properties那些用指定装饰的Attribute并提取Attribute数据......一次通过?
目前我首先进行PropertyInfo过滤,然后获取属性数据:
属性数据:
public class Weight
{
public string Name { get; set; }
public double Value { get; set; }
public Weight(string Name,double Value) {
this.Name = Name;
this.Value = Value;
}
}
属性:
[AttributeUsage(AttributeTargets.Property)]
public class WeightAttribute : Attribute
{
public WeightAttribute(double val,[CallerMemberName]string Name=null)
{
this.Weight = new Weight(Name, val);
}
public Weight Weight { get; set; }
}
提取器:
private static IReadOnlyList<Weight> ExtractWeights(Type type)
{
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)
.Where(x => x.GetCustomAttribute<WeightAttribute>() != null);
var weights = properties
.Select(x => x.GetCustomAttribute<WeightAttribute>().Weight)
.ToArray();
return weights;
}
正如您在我的Extractor方法中看到的那样,我首先过滤PropertyInfo[]然后获取数据。还有其他更有效的方法吗?
汪汪一只猫
慕无忌1623718
相关分类