Reputation: 1223
I search for a way to get an own attribute within a property.
Let me demonstrate what I'm searching
I want to use a property for float/double values to give a tolerence for comparision.
e.g.
[FieldAttribute(CompareTolerance = 0.001)]
public float SomeProperty
{
get { return this.someProperty; }
set
{
if (Math.Abs(someProperty- value) > 0.001) // here i would like to use somthing like '> FieldAttribute.CompareTolerance'
this.someProperty = value;
}
}
From another class i would use
PropertyInfo propertyInfo = someobject.GetType().GetProperty("SomeProperty");
if (null != propertyInfo)
{
Attribute attribute = Attribute.GetCustomAttribute(propertyInfo, typeof (FieldAttribute));
FieldAttribute fieldAttribute = attribue as FieldAttribute;
return fieldAttribute.CompareTolerance;
}
...
So in the end i would only need
if(Math.Abs(someProperty - value) < someobject.CompareTolerance("SomeField")) ... values are equal
But is there a way to get an atribute within a property without using reflection each time ( this.CompareTolerance("SomeField") )
Upvotes: 0
Views: 101
Reputation: 8008
There is no other way around reflection for this except maybe code generation. You could consider a T4 template that generates a partial definition of your class with the desired getter/setter (might need to be placed in partial methods) code after extracting the values with reflection from the attribute. Then compile again.
I'm not sure why everyone seems to be avoiding generating code lately. T4 makes this a pleasure in modern versions of VS.
Upvotes: 1