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)
目前,我有一些解决方法可以让编译器理解:
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
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)