Is it possible to have a delegate as attribute parameter?

前端 未结 4 760
醉话见心
醉话见心 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 08:06

    Other possible workaround is creating abstract base Attribute type with abstract method matching your delegate definition, and then implementing the method in concrete Attribute class.

    It has following benefits:

    • Annotation is more concise and clean (DSL like)
    • No reflection
    • Easy to reuse

    Example:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple=false, Inherited=true)]
    public abstract class GetConnectionAttribute : Attribute
    {
        public abstract IPropertySet GetConnection();
    }
    
    public class GetConnectionFromPropertySetAttribute : GetConnectionAttribute
    {
        public override IPropertySet GetConnection()
        {
            return new PropertySetClass();
        }
    }
    
    [GetConnectionFromPropertySet]
    public class Test
    {
    }
    

提交回复
热议问题