gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:27:32 26 4
gpt4 key购买 nike

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

我目前正在防范可能为空的潜在字符串 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);

Hint / warning from VS : 'filename' may be null here.

目前,我有一些解决方法可以让编译器理解:
  • 使用空值原谅运算符 filename!
  • 使用 #pragma warning disable CS8604 // Possible null reference argument. 禁用警告
  • 添加另一个空检查 if(string == null || string.IsNullOrWhitespace(filename))

  • 但似乎没有一个令人满意,主要是因为我需要为每次调用 IsNullOrEmpty 重复解决方法。 .

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

    最佳答案

    如果您没有 .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
    您还需要像这样激活 NotNullWhen 属性:
    namespace System.Diagnostics.CodeAnalysis
    {
    [AttributeUsage(AttributeTargets.Parameter)]
    public sealed class NotNullWhenAttribute : Attribute {
    public NotNullWhenAttribute(bool returnValue) => ReturnValue = returnValue;
    public bool ReturnValue { get; }
    }
    }

    关于string - C#8 nullable : string. IsNullOrEmpty 不被编译器理解为有助于防止空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60391867/

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