可为空的引用类型 - 通过接受的参数返回类型可为空性



我有一个接受字符串的方法Foo。如果字符串为 null,它会执行某些操作,如果不是,它会执行其他操作(null 是有效值)。然后,它返回相同的字符串。

下面是在 C# 8.0 中禁用了可为空的引用类型的 Foo:

string Foo(string s)
{
    // Do something with s.
    return s;
}
void Bar()
{
    string s = "S";
    string s2 = Foo(s);
    string n = null;
    string n2 = Foo(n);
}

启用可为 null 的引用类型后,string n = null会发出警告。这是有道理的,因为string不再可为空。我将其类型转换为string?

void Bar()
{
    string s = "S";
    string s2 = Foo(s);
    string? n = null; // X
    string? n2 = Foo(n);
}

现在Foo(n)警告我 Foo 最近不喜欢可为空的字符串。这也是有道理的 - Foo 应该接受一个可为空的字符串,因为它同时支持空值和非空值。我更改了它的参数,因此将类型返回到string?

string? Foo(string? s)
{
    // Do something with s.
    return s;
}

这次是string s2 = Foo(s),抱怨Foo返回string?,而我试图将其分配给string

有没有办法让我让流分析理解这样一个事实,即当我为 Foo 提供string(而不是string?)时,它的返回值不能为空?

当参数 s 不为 null 时,这可能会使返回值不为 null。

// using System.Diagnostics.CodeAnalysis;
[return: NotNullIfNotNull("s")]
string? Foo(string? s)
{
    // Do something with s.
    return s;
}

是的,只有两种方法。 一个接受string?并返回string?,另一个接受string并返回string。 您可能希望根据后者实现前者(检查 null,如果非 null,则调用其他方法,否则处理 null 情况)。

使用两种方法是确保返回类型因输入类型而异的方法。

最新更新