I want to make an attribute that will allow me to specify some method applied to property, like this:
public class MyClass
{
[MyAttribute(Converter="ConverterMethod")]
public string Prop { get; set; }
public static string ConverterMethod(string src)
{
return src + " converted";
}
}
What is the 'right' way to do that?
Here are the ways that I see:
Dictionary<string, Func<string, string>>
and populate it with corresponding methods during runtime. Then extract method using attribute's string property as a key. This method is more resistant to refactoring, if I rename method everything will work (dictionary key will remain the same though)typeof(ConverterImpl)
to attribute. Then create an instance of converter during runtime and use its interface to convert values. This way seem the best to me but I never used Type
properties in attributes and don't even know if they are serialized well.Which approach is best? Is there other approaches? How people usually do such things?
The first option is pretty normal, and has the advantage of simplicity. You are right to say the it is a little susceptible to refactoring, but... this is rarely a "real" problem.
Another (fourth) approach, however, would be to make the attribute abstract with an abstract method, and subclass it with the conversion code in the attribute - then at runtime you can get the attribute (as the base-attribute) and just call the virtual method, this approach s common in things like MVC.
Personally, I usually just use the first option, along with unit tests for safety (in case of refactoring etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With