有可能有一个委托作为属性参数?

是否有可能有委托作为参数的参数?

喜欢这个:

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 { } 

如果不可能,那么明智的select是什么?

不,您不能将委托作为属性构造函数参数。 查看可用的types: 属性参数types
作为一种解决方法(虽然这是hacky和容易出错),你可以用reflection来创build一个委托 :

 [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(delegateType, delegateType.GetMethod(delegateName)); } } [Workspace(typeof(TestDelegate), "GetConnection")] public class Test { } 

其他可能的解决方法是创build抽象基本属性types与抽象方法匹配您的委托定义,然后在具体的属性类中实现该方法。

它有以下好处:

  • 注释更加简洁干净(类似DSL)
  • 没有反思
  • 易于重复使用

例:

 [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 { } 

我通过使用enum和代表映射数组解决了这个问题。 虽然我真的很喜欢使用inheritance的想法,但是在我的场景中,我需要编写几个子类来做相对简单的事情。 这也应该是可重构的。 唯一的缺点是你必须确保数组中的委托索引对应于枚举值。

 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); }