gpt4 book ai didi

delegates - 通过委托(delegate)执行可重写方法时,Invoke() 和 BeginInvoke() 的行为不同

转载 作者:行者123 更新时间:2023-12-04 12:15:34 24 4
gpt4 key购买 nike

谁能告诉我为什么这段代码的行为方式如此?查看代码中嵌入的注释...

我在这里错过了一些非常明显的东西吗?

using System;
namespace ConsoleApplication3
{
public class Program
{
static void Main(string[] args)
{
var c = new MyChild();
c.X();
Console.ReadLine();
}
}

public class MyParent
{
public virtual void X()
{
Console.WriteLine("Executing MyParent");
}
}

delegate void MyDelegate();

public class MyChild : MyParent
{
public override void X()
{
Console.WriteLine("Executing MyChild");
MyDelegate md = base.X;

// The following two calls look like they should behave the same,
// but they behave differently!

// Why does Invoke() call the base class as expected here...
md.Invoke();

// ... and yet BeginInvoke() performs a recursive call within
// this child class and not call the base class?
md.BeginInvoke(CallBack, null);
}

public void CallBack(IAsyncResult iAsyncResult)
{
return;
}
}
}

最佳答案

我还没有答案,但我有一个我认为是更清晰的程序来证明奇怪:

using System;

delegate void MyDelegate();

public class Program
{
static void Main(string[] args)
{
var c = new MyChild();
c.DisplayOddity();
Console.ReadLine();
}
}

public class MyParent
{
public virtual void X()
{
Console.WriteLine("Executing MyParent.X");
}
}

public class MyChild : MyParent
{
public void DisplayOddity()
{
MyDelegate md = base.X;

Console.WriteLine("Calling Invoke()");
md.Invoke(); // Executes base method... fair enough

Console.WriteLine("Calling BeginInvoke()");
md.BeginInvoke(null, null); // Executes overridden method!
}

public override void X()
{
Console.WriteLine("Executing MyChild.X");
}
}

这不涉及任何递归调用。结果仍然是同样的奇怪:
Calling Invoke()
Executing MyParent.X
Calling BeginInvoke()
Executing MyChild.X

(如果您同意这是一个更简单的重现,请随时替换原始问题中的代码,我会将其从我的答案中删除:)

老实说,这对我来说似乎是一个错误。我会多挖一点。

关于delegates - 通过委托(delegate)执行可重写方法时,Invoke() 和 BeginInvoke() 的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/229508/

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