And*_*nas 15 .net c# virtual overriding optional-parameters
在下面的代码中,对Method2的调用接收Value参数为False,即使基类根本没有声明参数的默认值,派生类声明True为默认值.
可以认为(在这里的类似示例中已经完成:在重写方法上使用C#可选参数)编译器首先使用基类的方法声明(这是正确的,因为可以通过对Method1调用前缀来更改此行为this.),但是在这种情况下,基数根本不会声明默认值.
对此有合理的解释吗?
using System;
class Base
{
public virtual bool Method1(bool Value) { return true; }
public virtual bool Method2(bool Value) { return true; }
}
class Derived : Base
{
public override bool Method1(bool Value = true)
{
return Value;
}
public override bool Method2(bool Value = true)
{
return Method1();
}
}
class Program
{
static void Main(string[] args)
{
Derived a = new Derived();
Console.WriteLine("Call to Method1, expected: True, got: {0}", a.Method1());
Console.WriteLine("Call to Method2, expected: True, got: {0}", a.Method2());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Call to Method1, expected: True, got: True Call to Method2, expected: True, got: False
| 归档时间: |
|
| 查看次数: |
2901 次 |
| 最近记录: |