c# - 抽象类中的可选参数覆盖派生

标签 c# abstract-class optional-parameters

<分区>

在抽象类中

public abstract class base
    {
        abstract public int Func(bool flag = true);
    }

我对派生版本进行了更改:

public class derived : base
    {
        public override int Func(bool flag = false){}
    }

调试显示编译器默认使用 true。我不这么认为,为什么它会这样?

最佳答案

此行为在 C# 语言规范的第 7.5.1.1 节(相应的参数,强调我的)中有说明:

For each argument in an argument list there has to be a corresponding parameter in the function member or delegate being invoked. The parameter list used in the following is determined as follows:

  • For virtual methods and indexers defined in classes, the parameter list is picked from the most specific declaration or override of the function member, starting with the static type of the receiver, and searching through its base classes

在绑定(bind)(将调用方法关联到调用的过程)期间,编译器使用上述规则找到一个参数列表,然后找到一组符合该参数列表的候选方法。其中最好的一个被挑选出来并绑定(bind)到调用。
拿这段代码:

BaseClass b = new DerivedClass( );
b.Func( );

在绑定(bind)期间,使用的参数列表是在 BaseClass.Func 中声明的(因为它是 b 的静态类型),候选方法集是 BaseClass.FuncDerivedClass.Func(据说它们是适用的,因为两个参数列表都对应于所选择的那个)。然后 DerivedClass.Func 被确定为最佳候选者,正如预期的那样,因此绑定(bind)到调用 使用 BaseClass.Func 的参数列表,因此使用 flag = true

您可以在§7.5.3(过载解决方案)中找到更多详细信息。最后,如果您想知道,抽象方法被认为是虚拟的,如 §10.6.6(抽象方法)中所述:

An abstract method declaration introduces a new virtual method but does not provide an implementation of that method.

关于c# - 抽象类中的可选参数覆盖派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452473/

相关文章:

C# - 如何使方法仅对继承方法基类的类可见

python - 为什么 AbstractSet 不包括并集和交集?

C++ 从 protected 抽象/派生类创建变量

c# - 带有可选参数的 Web 服务方法

c# - 如何使用编码运行 rdlc

c# - 为什么 main() 中的 try-catch 不好?

c# - 日期时间 SQL 问题

c# - 在 .NET Core 6.0 Razor 页面应用程序中配置 Serilog 的正确方法是什么?

c# - 我可以检索方法中参数的默认值吗?

c++ - 是否可以指定一个空的 std::vector 作为默认参数?