在抽象类中
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.Func
和 DerivedClass.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.