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

我是否在这里遗漏了一些明显的东西?

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

(如果您同意这是一个简单的复制程序,请随时替换原始问题中的代码,然后从答案中删除它:)

老实说,这对我来说似乎是个bug。我会再挖一点。

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

10-13 04:01