Is there any method to select only the properties
that are decorated with a specified Attribute
and extract the Attribute
data ...all in one pass?
Currently i am first doing a PropertyInfo
filtering and then i am getting the Attribute data:
Attribute data
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;
}
}
Attribute
[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; }
}
Extractor
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;
}
As you can see in my Extractor
method i am first filtering the PropertyInfo[]
and then getting the data's.Is there any other more efficient way?
Aucun commentaire:
Enregistrer un commentaire