C#命名参数,继承和重载惊喜

fer*_*anj 6 inheritance overloading named-parameters c#-4.0

我正在阅读有关C#4.0的一些演示文稿,最后演示者使用以下代码发布了一个测验.

using System;
class Base {
    public virtual void Foo(int x = 4, int y = 5) {
        Console.WriteLine("B x:{0}, y:{1}", x, y);
    }
}

class Derived : Base {
    public override void Foo(int y = 4, int x = 5) {
        Console.WriteLine("D x:{0}, y:{1}", x, y);
    }
}

class Program {
    static void Main(string[] args) {
        Base b = new Derived();
        b.Foo(y:1,x:0);
    }
}

// The output is 
// D x:1, y:0
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么产生输出(没有演示者离线阅读演示文稿的问题).我在期待

D x:0, y:1
Run Code Online (Sandbox Code Playgroud)

我在网上搜索找到答案,但仍然无法找到答案.有人可以解释一下吗?

Dan*_*rth 3

原因似乎如下:您正在调用FooBase因此它从 中获取参数名称Base.Foo。由于x是第一个参数,并且y是第二个参数,因此在将值传递给重写方法时将使用此顺序。