Inheritance C#命名参数、继承和重载
我正在看一些关于C#4.0的演示,最后演示者发布了一个带有以下代码的测试Inheritance C#命名参数、继承和重载,inheritance,c#-4.0,named-parameters,overloading,Inheritance,C# 4.0,Named Parameters,Overloading,我正在看一些关于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)
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
我在网上搜寻答案,但还是找不到。有人能解释一下吗?原因似乎如下:您在
Base
上调用Foo
,因此它从Base.Foo
中获取参数名称。由于x
是第一个参数,而y
是第二个参数,因此将值传递给重写方法时将使用此顺序。这与命名参数无关。了解什么是多态性。问题是任何开发人员都会因为多态性而期望调用派生的.Foo。因此,有人认为派生.Foo中的命名参数将被接受是正常的。但由于这是运行时多态性,编译器使用Base.Foo中的参数名。