为什么可以将 null 分配给 Nullable 变量?
Why can you assign null to a Nullable variable?
为什么要编译下面的行?对我来说,Nullable<double>
是一个结构,我们不能为这种类型的变量分配值 "null"。
Nullable<double> someVar = null;
赋值运算符不应被覆盖,但它可能是一些语法糖并且编译器知道它必须将其更改为 ?
Nullable<double> someVar = new Nullable<double>();
someVar.Value = null;
编译器和语言规范有特殊的神奇支持,使 null
文字可转换为 Nullable<T>
。
- A null literal. An expression with this classification can be implicitly converted to a reference type or nullable type.
在规格上。
第 6.1.5 节说:
6.1.5 Null literal conversions
An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type
4.1.10 说:
4.1.10 Nullable types
A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable, and the two forms can be used interchangeably.
...
Implicit conversions are available from the null literal to T? (§6.1.5) and from T to T? (§6.1.4)
(粗体是我的)
为什么要编译下面的行?对我来说,Nullable<double>
是一个结构,我们不能为这种类型的变量分配值 "null"。
Nullable<double> someVar = null;
赋值运算符不应被覆盖,但它可能是一些语法糖并且编译器知道它必须将其更改为 ?
Nullable<double> someVar = new Nullable<double>();
someVar.Value = null;
编译器和语言规范有特殊的神奇支持,使 null
文字可转换为 Nullable<T>
。
- A null literal. An expression with this classification can be implicitly converted to a reference type or nullable type.
在规格上。
第 6.1.5 节说:
6.1.5 Null literal conversions
An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type
4.1.10 说:
4.1.10 Nullable types
A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable, and the two forms can be used interchangeably.
...
Implicit conversions are available from the null literal to T? (§6.1.5) and from T to T? (§6.1.4)
(粗体是我的)