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

Posted

技术标签:

【中文标题】C#8 nullable : string.IsNullOrEmpty 不被编译器理解为有助于防止 null【英文标题】:C#8 nullable : string.IsNullOrEmpty is not understood by compiler as helping for guarding against null 【发布时间】:2020-06-09 00:35:30 【问题描述】:

我将 C# 8 与 .NET 框架 4.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);

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

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

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

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

【问题讨论】:

也许这个链接会有所帮助:https://github.com/dotnet/roslyn/issues/37995 C# 8.0 仅在实现 .NET Standard 2.1 的平台上受支持,而不是 .NET 框架...也就是说,如果您自己定义了 DoesNotReturnIf 属性,那么您可以定义自己的 Assert 方法并且改用那个。 @JulienCouvreur 不正确:***.com/a/57020770/2729609 C#8 可用于 .Net-Framework。 @SebastianSchumann 很抱歉,但正确提供的摘要得出的结论是“Microsoft 未正式支持 C# 8/.NET Framework 组合。”。请注意,“支持”与“未被禁用,并且仍然可以主要为喜欢冒险的人工作”不同。 @JulienCouvreur 是的,对。至少部分支持!但是应该有助于解决我的问题的精确属性仅在“完全支持”中可用,即使用 .NET Core 3 【参考方案1】:

如果您没有 .net standard 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; 
    

【讨论】:

以上是关于C#8 nullable : string.IsNullOrEmpty 不被编译器理解为有助于防止 null的主要内容,如果未能解决你的问题,请参考以下文章

C# 8.0 可空(Nullable)给ASP.NET Core带来的坑

如何为整个项目启用 C# 8.0 的 Nullable Reference Types 功能

int c=8;和int? c=8;有啥区别,作用是?

C# 8 中的 Non-Nullable 引用类型的默认值是多少?

可空引用类型的注释只能在“#nullable”上下文中的代码中使用

C#--可空类型(Nullable)