int? x = null;
x = x + 1; // Works, but x remains null
我希望编译器尝试将 x 转换为 int,但显然它没有。
由 280Z28 编辑:已更改 NullReferenceException
至 InvalidOperationException
,这就是 Nullable<T>.Value
当 HasValue
时抛出是假的。
最佳答案
这是根据提升二元运算符的规范。来自 §7.2.7:
For the binary operators
+ - * / % & | ^ << >>
a lifted form of an operator exists if the operand and result types are all non-nullable value types. The lifted form is constructed by adding a single
?
modifier to each operand and result type. The lifted operator produces a null value if one or both operands are null (an exception being the & and | operators of the bool? type, as described in §7.10.3). Otherwise, the lifted operator unwraps the operands, applies the underlying operator, and wraps the result.
推理是这样的:你要想到null
对于可空类型,意思是“我不知道值是什么”。 “我不知道”加一的结果是什么? “我不知道。”因此,结果应该是 null
.
关于c# - 为什么尝试添加到空值不会抛出 InvalidOperationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2156220/