gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:11:01 25 4
gpt4 key购买 nike

在编写涉及手动类型检查的测试时,我发现 null不评估为 Nullable<> 的实例类型,例如对于类型 Nullable<int> (与 int? 相同)以下说法是错误的

null is int?

同时分配 nullint?已验证。为什么会这样?

最佳答案

那么,为什么 nullable 应该是特殊的?这不代表任何引用类型,句点:

var isObject = null is object;

会给你一个编译时错误:

Error CS0184: The given expression is never of the provided ('object') type

Nullable<T>这里是一条红鲱鱼。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com