小编Jas*_* Yu的帖子

如何识别泛型类型的可为空引用类型?

在启用了可为空的 C# 8 中,有没有办法为泛型类型识别空的引用类型?

对于null 的值类型,有一个专用于它的部分。 https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#how-to-identify-a-nullable-value-type

我们正在尝试根据泛型类型进行可选的空检查

#nullable enable
public static Result<T> Create<T>(T value)
{
   if (!typeof(T).IsNullable() && value is null)
      throw new ArgumentNullException(nameof(value));

   // Do something
}

public static bool IsNullable(this Type type)
{
   // If type is SomeClass, return false
   // If type is SomeClass?, return true
   // If type is SomeEnum, return false
   // If type is SomeEnum?, return true
   // If type is string, return false
   // …
Run Code Online (Sandbox Code Playgroud)

c# generics c#-8.0 nullable-reference-types

6
推荐指数
1
解决办法
957
查看次数

标签 统计

c# ×1

c#-8.0 ×1

generics ×1

nullable-reference-types ×1