在C#8中,为什么对新表达式进行类型推断会导致可为空的引用? [英] In C# 8, why does type inference on new expressions result in nullable references?

查看:58
本文介绍了在C#8中,为什么对新表达式进行类型推断会导致可为空的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有C#8代码:

class Foo {}

后来:

#nullable enable
var bar = new Foo();

然后, bar 的类型为 Foo?.这似乎很不正确,因为 new 表达式不能返回 null .为什么 bar 是可为空的引用?我什至查找了

Then the type of bar is Foo?. This seems clearly incorrect, as a new expression can't return null. Why would bar be a nullable reference? I even looked up the Nullable Reference Type Specification, and found the following:

永远不会为空的表达式

以下表达式形式的null状态始终为"not null":

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

  • ...
  • new 表达式(对象,委托,匿名对象和数组创建表达式)
  • ...
  • ...
  • new expressions (object, delegate, anonymous object and array creation expressions)
  • ...

还有:

var的类型推断

由var声明的局部变量推断的类型由初始化表达式的null状态告知.

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

var x = E;

如果 E 的类型是可为空的引用类型 C?,并且 E 的空状态为"not null";那么为 x 推断的类型为 C .否则,推断的类型为 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.

根据 var 的注释上下文,如上所述确定了为 x 推断出的类型的可为空性,就好像该类型已在那个位置.

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吗?.我想念什么?

So based on everything I can find in the spec, bar in my very simple example should be of type Foo, not type Foo?. What am I missing?

推荐答案

如果 var 要从表达式中推断其可空性,那么在许多情况下,您将无法分配null .例如, var s ="; .进行了讨论以允许 var?表示该类型的可为空版本",但是存在一些问题.常规的 var 是否会被限制为只能推断出不可为空的类型?

If var were to infer its nullability from the expression, then in many instances you would not be able to assign a null to it later on. For example, var s = "";. There was a discussion to allow var? to express "the nullable version of the type", but it had several issues. Would the regular var be restricted to infer a non-nullable type?

如果是,则(1)由于用户需要添加更多?批注,我们正在制造采用上的痛苦;(2)我们使用 var 模式具有不一致的可空性(3)存在一些具有可空值类型( int?)的问题.如果否,那么代码的意图将不是很清楚. var?将清楚地指示可为空的类型,但是 var 将为可为空和不可为空的混合包.

If yes, then (1) we're creating adoption pain as users need to add more ? annotations, (2) we have an inconsistent nullability with var pattern which had already shipped, (3) there are some questions with nullable value types (int?). If no, then the intent of the code would not be very clear. var? would clearly indicate a nullable type, but var would be a mixed bag of nullable and non-nullable.

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆