c# - 为什么 null 不是 Nullable<> 类型的实例?

标签 c# .net types

在编写涉及手动类型检查的测试时,我发现 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:

  1. If E is an anonymous function, a compile-time error occurs
  2. 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. (...)

粗体部分用于澄清。

阅读thisthis answer了解更多信息。

关于c# - 为什么 null 不是 Nullable<> 类型的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45011257/

相关文章:

c# - 如何从 C# 调用 native VC++6 库(以 std::string 作为参数)

.net - 由于以下错误 : 80040154,检索 CLSID {xxxx} 组件的 COM 类工厂失败

C#:如何设置 DNS 解析超时?

c++ - 这个类声明是什么意思?

c# - 在 Button 事件处理程序方法 Xamarin Forms 中获取控件名称

c# - 如何在 ASP.NET 中模拟缓慢的页面加载?

c# - TemplateBinding 不适用于文本框文本

java - Collection<?> 和 Collection<T> 有什么区别

c++ - 在 C/C++ 中返回指向类/结构中任何字段的指针

C# - 将私有(private)属性序列化为属性(数据协定)