谁能告诉我为什么这段代码的行为方式呢?查看代码中嵌入的评论......
我错过了一些非常明显的东西吗?
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; } } }
Jon Skeet.. 5
我还没有答案,但我有一个我认为是一个更清晰的程序,以证明奇怪:
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
(如果您同意这是一个更简单的repro,请随意替换原始问题中的代码,我将从我的答案中删除它:)
说实话,这对我来说就像一个小虫.我会再挖掘一下.
我还没有答案,但我有一个我认为是一个更清晰的程序,以证明奇怪:
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
(如果您同意这是一个更简单的repro,请随意替换原始问题中的代码,我将从我的答案中删除它:)
说实话,这对我来说就像一个小虫.我会再挖掘一下.