【问题标题】:C# Named parameters, Inheritance and overloading surpriseC# 命名参数、继承和重载惊喜
【发布时间】: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


【解决方案1】:

原因似乎如下:您在Base 上调用Foo,因此它从Base.Foo 中获取参数名称。因为x 是第一个参数,y 是第二个参数,所以在将值传递给被覆盖的方法时将使用此顺序。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    相关资源
    最近更新 更多