gpt4 book ai didi

c# - 双引用委托(delegate)

转载 作者:行者123 更新时间:2023-11-30 22:51:32 25 4
gpt4 key购买 nike

抱歉,我没有描述真正的问题。我决定编辑我的问题。我怎样才能简化我的例子来省去 GetDelegate统计功能?C的类很多其中,对于特定事件 E , 需要执行操作 Cd .但在执行 Cd 的 Action 之前,您需要检查权限。权限检查的结果,我在类的主流中得到A , 方法回调。并且已经根据检查结果决定是否开始操作 Cd .也就是说,在类里面 C事件 E , 有必要设置 Cd对于类中声明的委托(delegate) A .从类 A调用Cd如果获得许可。在实际应用中,存在多线程。

    public delegate void D();
public delegate ref D GetD();
class A//This is Thread 1
{
static D d;
static void Main(string[] args)
{
C c1 = new C(GetDelegate, "NAME1");
C c2 = new C(GetDelegate, "NAME2");
Console.ReadLine();
}
static ref D GetDelegate()
{
return ref d;
}
void OnPermissionsResult(bool result)//This is a permission check callback method.
{
if (result)
{
d();
}
else
{
Console.WriteLine("You do not have permission.\r");
}
}
}
class C//This is Thread 2
{
string name;
GetD getd;
public C(GetD getd, string name)
{
this.name = name;
this.getd = getd;
}
void M()
{
//This is example of event 'E'
button.Click += () =>
{
getd() = () =>//This is Ation 'Cd'
{
Console.WriteLine($"Action: {name}\r");
};
CheckPermissions();//Begin check permission.
};
}
}

最佳答案

正如评论中所指出的,这是一件奇怪的事情,因此听起来你在问一个“XY 问题”。 XY 问题是“我想出了一个问题的奇怪解决方案,那个奇怪的解决方案不太正确,现在我要问一个没有多大意义的问题,因为它是关于我的奇怪解决方案,而不是关于我真正的问题”。问一个真正的问题!

也就是说,如果我们想表示“我可以读写另一个类的属性”,通常我们会做的不是使用返回引用的委托(delegate),而是使用具有属性的接口(interface)。我会编写您的代码——假设我会编写它来解决您的实际问题——像这样:

public delegate void D();
internal interface I
{
D D { get; set; }
}
class P : I
{
public D D { get; set; }
static void Main()
{
(new P()).M();
}
private void M()
{
C c1 = new C(this, "NAME1");
C c2 = new C(this, "NAME2");
c1.SetD();
this.D();
c2.SetD();
this.D();
}
}
class C
{
private I i;
private string name;
public C(I i, string name)
{
this.name = name;
this.i = i;
}
public void SetD()
{
this.i.D = () => { whatever };
}
}

不需要乱用静态字段或 ref 返回委托(delegate)。

关于c# - 双引用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59091087/

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