Is it possible to have a delegate as the parameter of an attribute?
Like this:
public delegate IPropertySet ConnectionPropertiesDelegate(); public static class TestDelegate { public static IPropertySet GetConnection() { return new PropertySetClass(); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface,AllowMultiple=false,Inherited=true)] public class WorkspaceAttribute : Attribute { public ConnectionPropertiesDelegate ConnectionDelegate { get; set; } public WorkspaceAttribute(ConnectionPropertiesDelegate connectionDelegate) { ConnectionDelegate = connectionDelegate; } } [Workspace(TestDelegate.GetConnection)] public class Test { }
And if its not possible, what are the sensible alternatives?
You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.
C# provides special syntax for invoking a delegate. When a non- null delegate instance whose invocation list contains one entry, is invoked, it invokes the one method with the same arguments it was given, and returns the same value as the referred to method.
The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are: One of the following types: bool , byte , char , double , float , int , long , sbyte , short , string , uint , ulong , ushort . The type object . The type System.
A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.
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 { }
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