在编写涉及手动类型检查的测试时,我发现 null
不评估为 Nullable<>
的实例类型,例如对于类型 Nullable<int>
(与 int?
相同)以下陈述是错误的
null is int?
分配null
时至int?
已验证。为什么会这样?
最佳答案
那么,为什么可空值应该是特殊的?这不代表任何引用类型,句号:
var isObject = null is object;
会给你一个编译时错误:
Error CS0184: The given expression is never of the provided ('object') type
Nullable<T>
这是一个转移注意力的事情。
null
的类型是 null 类型,并且它可以分配给任何引用类型或可为 null 的类型,因为存在隐式转换(第 2.4.4.6 节)。
这个is
根据规范的运算符按以下方式工作(第 7.10.10 节):
The is operator is used to dynamically check if the run-time type of an object is compatible with a given type. The result of the operation E is T, where E is an expression and T is a type, is a boolean value indicating whether E can successfully be converted to type T by a reference conversion, a boxing conversion, or an unboxing conversion. The operation is evaluated as follows, after type arguments have been substituted for all type parameters:
- If E is an anonymous function, a compile-time error occurs
- If E is a method group or the null literal, or if the type of E is a reference type or a nullable type and the value of E is null, the result is false. (...)
粗体部分用于澄清。
阅读this和 this answer了解更多信息。
关于c# - 为什么 null 不是 Nullable<> 类型的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45011257/