Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make method reference in attribute parameter

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:

  1. Make string property and extract corresponding method with reflection during runtime
  2. Make 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)
  3. Make 'IConverter' interface and pass 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?

like image 898
Poma Avatar asked Feb 26 '12 05:02

Poma


1 Answers

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).

like image 200
Marc Gravell Avatar answered Oct 17 '22 06:10

Marc Gravell