C# 命名参数、继承和重载惊喜
我正在观看一些有关 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
我会在网上搜索答案,但仍然找不到。有人可以解释一下吗?
I was going through some presentation regarding C# 4.0 and in the end the presenter posted a quiz with the following code.
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
I couldn't figure out why that output is produced (problem of reading the presentation offline without the presenter). I was expecting
D x:0, y:1
I searched the net to find the answer but still couldn't find it. Can some one explain this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
原因似乎如下:您正在
Base
上调用Foo
,因此它从Base.Foo
获取参数名称。由于x
是第一个参数,y
是第二个参数,因此在将值传递给重写方法时将使用此顺序。The reason seems to be the following: You are calling
Foo
onBase
, so it takes the parameter names fromBase.Foo
. Becausex
is the first parameter andy
is the second parameter, this order will be used when passing the values to the overriden method.