Is it possible to have a delegate as attribute parameter?

前端 未结 4 797
醉话见心
醉话见心 2020-11-28 07:41

Is it possible to have a delegate as the parameter of an attribute?

Like this:

public delegate IPropertySet ConnectionPropertiesDelegate();

public s         


        
4条回答
  •  余生分开走
    2020-11-28 07:54

    I solved this by using an enum and a mapping array of delegates. Although I really like the idea of using inheritance, in my scenario that would require me to write several child classes to do relatively simple stuff. This should be refactorable as well. The only drawback is that you have to make sure to make the delegate's index in the array corresponds to the enum value.

    public delegate string FormatterFunc(string val);
    
    public enum Formatter
    {
        None,
        PhoneNumberFormatter
    }
    
    public static readonly FormatterFunc[] FormatterMappings = { null, PhoneNumberFormatter };
    
    public string SomeFunction(string zzz)
    {
       //The property in the attribute is named CustomFormatter
       return FormatterMappings[(int)YourAttributeHere.CustomFormatter](zzz);
    }
    

提交回复
热议问题