是否有可能有一个委托作为属性参数? [英] Is it possible to have a delegate as attribute parameter?

查看:107
本文介绍了是否有可能有一个委托作为属性参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这样的:

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?

推荐答案

没有,你不能有一个委托作为属性构造函数的参数。见可用的类型:属性参数类型结果
作为一种变通方法(虽然它的哈克,而且容易出错),您可以创建具有反射一个委托:

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(delegateType, delegateType.GetMethod(delegateName));
    }
}

[Workspace(typeof(TestDelegate), "GetConnection")]
public class Test
{
}

这篇关于是否有可能有一个委托作为属性参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆