gpt4 book ai didi

c# - 是否可以将委托(delegate)作为属性参数?

转载 作者:IT王子 更新时间:2023-10-29 03:54:51 25 4
gpt4 key购买 nike

是否可以将委托(delegate)作为属性的参数?

像这样:

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

如果不可能,有哪些明智的选择?

最佳答案

不,您不能将委托(delegate)作为属性构造函数参数。查看可用类型:Attribute parameter types
作为一种解决方法(尽管它很笨拙且容易出错),您可以创建一个 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
{
}

关于c# - 是否可以将委托(delegate)作为属性参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com