gpt4 book ai didi

c# - 在 C# 8 中,为什么对新表达式的类型推断会导致可空引用?

转载 作者:行者123 更新时间:2023-12-04 14:44:56 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Why does Visual Studio Type a Newly Minted Array as Nullable?

(3 个回答)


去年关闭。




如果我有 C# 8 代码:

class Foo {}
然后:
#nullable enable
var bar = new Foo();
然后是 bar的类型是 Foo? .这似乎显然不正确,如 new表达式无法返回 null .为什么会 bar是一个可为空的引用?我什至查了一下 Nullable Reference Type Specification ,并发现以下内容:

Expressions that are never null

The null state of the following expression forms is always "not null":

  • ...
  • new expressions (object, delegate, anonymous object and array creation expressions)
  • ...

并且:

Type inference for var

The type inferred for local variables declared with var is informed by the null state of the initializing expression.

var x = E;

If the type of E is a nullable reference type C? and the null state of E is "not null" then the type inferred for x is C. Otherwise, the inferred type is the type of E.

The nullability of the type inferred for x is determined as described above, based on the annotation context of the var, just as if the type had been given explicitly in that position.


因此,基于我在规范中可以找到的所有内容, bar在我非常简单的例子中应该是类型 Foo , 不是类型 Foo? .我错过了什么?

最佳答案

var如果要从表达式推断其可空性,那么在许多情况下您将无法分配 null以后再说吧。例如,var s = ""; .
有讨论允许 var?表达“类型的可为空版本”,但它有几个问题。请问正规var被限制为推断不可为空的类型?
如果是,那么 (1) 我们正在制造采用痛苦,因为用户需要添加更多 ?注释,(2) 我们与 var 的可空性不一致已经发布的模式,(3) 有一些可空值类型的问题 ( int? )。
如果不是,那么代码的意图就不是很清楚。 var?会清楚地表明一个可为空的类型,但 var将是可空和不可空的混合包。
var 推断可为空类型的决定被记录在LDM notes from 2019-12-18 .

关于c# - 在 C# 8 中,为什么对新表达式的类型推断会导致可空引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62685673/

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