c# - 不可为空的引用类型 : why is my object considered nullable by the compiler?

标签 c# .net-core nullable-reference-types

我有一个项目,我启用了新的 Nullable reference type feature

 <Nullable>enable</Nullable>

现在让我们考虑这段代码

public class Foo  {    }

var foo = new Foo();

编译器会考虑 foo变量可以为空( Foo? )。
这是为什么?我不明白。

现在使用 Nullable 引用类型功能启用返回的 Foo object 不应该为 null,因为它是不可为 null 的类型。

如果我希望它可以为空,我会指定它有一个 Foo?
那么为什么编译器说它是一个可为空的变量呢?

谢谢

编辑

这是我在这里描述的内容的屏幕截图。当您将鼠标悬停在 foo 上时多变的

Hover the foo variable

最佳答案

在最初的实现中,foo将被推断为 Foo .

然而,人们提示这妨碍了以下事情:

string? GetThing() => ...

var result = "";
if (condition)
{
    result = GetThing();
}

result被推断为 string ,然后是 result = GetThing()行导致警告:GetThing()返回 string? ,如果您尝试分配 string?,则会出现警告到 string .

解决方案是推断 result作为 string? ,但编译器知道它当前不为空(它的“流状态”是“NotNull”)。

这意味着:
string? GetThing() => ...

var result = "";

// No warning, as the compiler knows that result isn't null
int l1 = result.Length; 

if (condition)
{
    result = GetThing();
}

// Warning: the compiler knows 'result' might have been re-assigned
int l2 = result.Length; 

有关工作中的流动状态的其他示例,请参阅以下内容:
string? result = GetString();
if (result == null)
    throw new Exception();

// No warning: the compiler knows that result can't be null here: if it was,
// the exception above would have been thrown
int l1 = result.Length;
string? result = GetString();

// Warning: result might be null
int l1 = result.Length; 

// No warning: the compiler knows that result can't be null here: if it was,
// the line above would have thrown
int l2 = result.Length; 
string result = "hello";
if (result == null)
    Console.WriteLine("NULL!");

// Warning: because we checked for null above, the compiler assumes that we
// know something that it doesn't, and so result might be null.
int l1 = result.Length;

关于c# - 不可为空的引用类型 : why is my object considered nullable by the compiler?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62473332/

相关文章:

c# - "Non-nullable field is uninitialized"的编译器错误,即使已在InitializeComponents函数中对其进行了初始化

c# - 可空引用类型意外 CS8629 可空值类型可能为空且带有临时变量

c# - 使用 Microsoft Web Optimization 缩小 CSS 和 JavaScript

asp.net-core - 带有 AppplicationDbContext 的身份脚手架

.net-core - .NET Core 不支持 Nuget 包 Microsoft.AspNetCore.* 版本 5

c# - Dotnet 核心 2.2 libgdipplus 异常

c# - 如何在 Update() 内为 Unity VR 应用程序设计平滑的 UI 滚动?

c# - 如何使登录页面成为 ASP.NET MVC Web 应用程序中的启动页面?

c# - 用户安装和运行基于 .NET 3.5 的 ClickOnce 应用程序所需的最低权限是什么?

c# - 通过反射检查时缺少 NotNullAttribute