我正在阅读有关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
我无法弄清楚为什么会产生这样的输出(在没有演示者的情况下离线阅读演示文稿的问题)。我在期待
D x:0, y:1
我在网上搜索找到答案,但仍然无法找到答案。有人可以解释一下吗?
答案 0 :(得分:3)
原因似乎如下:您在Foo
上呼叫Base
,因此它从Base.Foo
获取参数名称。因为x
是第一个参数而y
是第二个参数,所以在将值传递给overriden方法时将使用此顺序。