Is it possible to have a delegate as attribute parameter?

前端 未结 4 763
醉话见心
醉话见心 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:56

    No, you cannot have a delegate as an attribute constructor parameter. See available types: Attribute parameter types
    As a workaround (although it's hacky and error prone) you can create a delegate with reflection:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false, Inherited = true)]
    public class WorkspaceAttribute : Attribute
    {
        public ConnectionPropertiesDelegate ConnectionDelegate { get; set; }
    
        public WorkspaceAttribute(Type delegateType, string delegateName)
        {
             ConnectionDelegate = (ConnectionPropertiesDelegate)Delegate.CreateDelegate(typeof(ConnectionPropertiesDelegate), delegateType, delegateName);
        }
    }
    
    [Workspace(typeof(TestDelegate), "GetConnection")]
    public class Test
    {
    }
    

提交回复
热议问题