C#8 nullable : string.IsNullOrEmpty 不被编译器理解为有助于防范 null

Pac*_*ac0 14 string c#-8.0 nullable-reference-types

我在 .NET 框架 4.8 中使用 C# 8

我目前正在防范可能为 null 的潜在字符串IsNullOrWhitespace(与IsNullOrEmpty)相同,但编译器仍在抱怨:

public MyImage? LoadImage(string? filename)
{
    if (string.IsNullOrWhiteSpace(filename))
    {
        return null;
    }
    return OtherMethod(filename); // here : warning from Visual Studio
}

// signature of other method :
public MyImage OtherMethod(string filepath);
Run Code Online (Sandbox Code Playgroud)

来自 VS 的提示/警告:此处的“文件名”可能为空。

目前,我有一些解决方法可以让编译器理解:

  • 使用空原谅运算符 filename!
  • 使用禁用警告 #pragma warning disable CS8604 // Possible null reference argument.
  • 添加另一个空检查 if(string == null || string.IsNullOrWhitespace(filename))

但似乎没有一个令人满意,主要是因为我需要为每次调用IsNullOrEmpty.

有没有其他方法可以告诉编译器 IsNullOrEmpty 有效地防止 null ?

ims*_*234 7

如果您没有 .net 标准 2.1 或 .net core 3,则 IsNullOrEmpty 不可为空。所以,我会为此创建一个扩展方法:

#nullable enable
public static class StringExt {
    public static bool IsNullOrEmpty([NotNullWhen(false)] this string? data) {
        return string.IsNullOrEmpty(data);
    }
}
#nullable restore
Run Code Online (Sandbox Code Playgroud)

您还需要像这样激活 NotNullWhen 属性:

namespace System.Diagnostics.CodeAnalysis
{
    [AttributeUsage(AttributeTargets.Parameter)]
    public sealed class NotNullWhenAttribute : Attribute {
        public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
        public bool ReturnValue { get; }
    }
}
Run Code Online (Sandbox Code Playgroud)