c# - 为什么尝试添加到空值不会抛出 InvalidOperationException?

标签 c# .net

int? x = null;
x = x + 1;  // Works, but x remains null

我希望编译器尝试将 x 转换为 int,但显然它没有。

由 280Z28 编辑:已更改 NullReferenceExceptionInvalidOperationException ,这就是 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/

相关文章:

c# - NetworkInterface.GetIPv4Statistics().BytesReceived - 它返回什么?

.net - OData Web API 操作参数反序列化

c# - 将 app.config 的 appsettings 部分分成两部分

c# - 尝试将字符串的第一个符号转换为 int,得到奇怪的值

c# - 当鼠标悬停在按钮上时更改光标图标

c# - efcore 2.2 中的 Multi-Tenancy 配置

.net - .net 中的方法调用有多昂贵

c# - 使用 Moq 确定方法是否被调用

c# - 对值在数据库中存储为 int 的枚举列进行排序

c# - 如何像windows一样 "copy-paste"文件