带有可选参数的构造函数是否会重载它?

Does constructor with optional-parameter overload it?

这是一个代码示例:

public List(int capacity = defaultCapacity) {
    items = new T[capacity];
}

C# 5 Language Specification Section 1.6.7中写着:

Instance constructors can be overloaded. For example, the List class declares two instance constructors, one with no parameters and one that takes an int parameter.

但是为此代码编译的 IL 不包含 2 个构造函数。它仅包含此声明:

.method public hidebysig specialname rtspecialname 
        instance void  .ctor([opt] int32 capacity) cil managed

表示可选参数为CLR级,由[opt]定义。

CLR 之后,没有运行时可以用 2 个重载构造函数表示此对象。

例如,如果我创建 2 个单独的构造函数而没有编译的可选参数 IL 将包含 2 个 .ctor -s.

我想澄清一下,如果语言规范说 class declares two instance constructors 是否意味着编译的 IL 也将包含 2 ctor-s。

可选参数,无论是用在方法上还是构造函数上,都不会引入额外的重载。相反,可选参数用 [opt] 标记,每当您调用它时未指定该参数值,该可选值将包含在您的编译代码中。

因此,当您更改可选参数的默认值时,您需要重新编译所有用法,以便将新值注入到所有调用中。如果您不这样做,将使用旧值。

更新

规范中的引述令人困惑。如果它谈论在 1.6.7 中定义的 List<T> 只有一个构造函数,带有可选参数,那就错了。