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

C#8 nullable:string.IsNullOrEmpty不被编译器理解为有助于防止null,string,c#-8.0,nullable-reference-types,String,C# 8.0,Nullable Reference Types,我正在将C#8与.NET framework 4.8一起使用 我目前正在防范使用IsNullOrWhitespace(与IsNullOrEmpty)可能为null的潜在字符串,但编译器仍在抱怨: public MyImage? LoadImage(string? filename) { if (string.IsNullOrWhiteSpace(filename)) { return null; } return OtherMethod(filen

我正在将C#8与.NET framework 4.8一起使用

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

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);

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

  • 使用空原谅运算符
    文件名
  • 通过使用
    #pragma warning disable CS8604//可能的空引用参数来禁用警告。
  • 如果(string==null | | | string.IsNullOrWhitespace(filename))为null
    添加另一个检查
但是这些都不令人满意,主要是因为我需要为每次调用
IsNullOrEmpty
重复解决方法


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

如果没有.net标准2.1或.net核心3,IsNullOrEmpty就不能为null做好准备。因此,我将为此创建一个扩展方法:

#nullable enable
public static class StringExt {
    public static bool IsNullOrEmpty([NotNullWhen(false)] this string? data) {
        return string.IsNullOrEmpty(data);
    }
}
#nullable restore
您还需要激活NotNullWhen属性,如下所示:

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

也许这个链接会有所帮助:C#8.0仅在实现.NET标准2.1的平台上受支持,而不是.NET framework。。。也就是说,如果您自己定义DoesNotReturnIf属性,那么您可以定义自己的Assert方法并使用该方法。@juliencouvruer这不正确:C#8可用于.Net Framework。@SebastianSchumann很抱歉,但提供的摘要正确地得出以下结论:“微软不正式支持C#8/.NET框架组合。”。请注意,“受支持”与“未被禁用,并且仍然可以为喜欢冒险的人工作”并不相同。@JulienCouvreur是的,对。至少它部分受支持!但应该有助于解决我的问题的确切属性仅在中提供”完全支持”,即使用.NET Core 3