【发布时间】:2011-09-12 10:17:57
【问题描述】:
我正在查看有关 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
我在网上搜索了答案,但仍然找不到。谁能解释一下?
【问题讨论】:
-
这与命名参数无关。了解什么是多态性。
-
问题是任何开发人员都希望 Derived.Foo 由于多态性而被调用。所以有人认为 Derived.Foo 中的命名参数会被取走是很正常的。但由于这是运行时多态性编译器使用 Base.Foo 中的参数名称。
标签: inheritance c#-4.0 named-parameters overloading