gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:02:06 26 4
gpt4 key购买 nike

我有一个项目,我启用了新的 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/

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