C# 8 使用实用方法验证参数

标签 c# nullable c#-8.0 nullable-reference-types

假设我有一个接受 nullable reference type 的方法喜欢:

int Func(string? param)
{
    return param.Length;
}

编译器正确地警告 param 应该检查 null

在 C# 8 之前,我习惯于使用这样的外部实用函数来验证参数:

public static class Validate
{
   public static void NotNull(object? value, string parameterName, string? field = null)
   {
     if (value == null) throw new ArgumentNullException(parameterName + (field == null ? string.Empty : "." + field));
   }
}
… 
int Func(string? param)
{
    Validate.NotNull(param, nameof(param));
    return param.Length;
}

在这种情况下,编译器似乎无法检测到参数 param 实际上在 Validate 方法内部检查了 null , 因此仍然提示。

没有其他方法可以直接测试方法内部的 null 值吗?

int Func(string? param)
{
    if (value == null) throw new ArgumentNullException(nameof(param));
    return param.Length;
}

最佳答案

你可以使用 [NotNull]为此,编译器了解到在调用 Validate.NotNull 之后,该值永远不会是 null

using System.Diagnostics.CodeAnalysis;

public static class Validate
{
   public static void NotNull([NotNull]object? value, string parameterName, string? field = null)
   {
     if (value == null) throw new ArgumentNullException(parameterName + (field == null ? string.Empty : "." + field));
   }
}

结果:这将不再发出警告:

int Func(string? param)
{
    Validate.NotNull(param, nameof(param));
    return param.Length;
}

旁注 - Func 方法的签名

当然问题是为什么 Func 方法没有签名:

int Func(string param) // no null allowed

如果那不可能,您还可以使用另一个属性 [DisallowNull] , 所以

int Func([DisallowNull] string? param) // gives warning if called with null compile time

旁注——更多属性

还有更多牛逼的属性

enter image description here

检查 Microsoft docs

关于C# 8 使用实用方法验证参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58886119/

相关文章:

c# - 在 C# 中使用外部文件和 MVVM 模式在运行时更改语言

c# - 玻璃表面上的发光标签控件

c# - .Net - 转换或转换装箱字节?,简而言之?还是整数?到整数?

c# - 新的 C# 8.0 switch 表达式的运算符优先级是什么?

c# - 禁止访问继承的 winform 控件

c# - 为什么不能在 Nullable<T> 简写上调用静态方法?

c# - 重载方法以支持引用类型和可空类型

c# - C#8“默认”是什么?对泛型类型做什么?

c# - 从异步方法返回IAsyncEnumerable

c# - 在 ASP.MVC 中创建一个通用的 NotFound View