【发布时间】:2020-09-21 16:53:49
【问题描述】:
在启用 nullable 的 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
我们正在尝试根据泛型类型进行可选的 null 检查
#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
// If type is string?, return true
// If type is int, return false
// If type is int?, return true
// etc
}
所以当T 不可为空时,以下将抛出ArgumentNullException
但是当T 可以为空时,允许值为空,例如
Create<Anything>(null); // throw ArgumentNullException
Create<Anything?>(null); // No excception
【问题讨论】:
-
@JasonYu 是否需要定义引用类型是否可以为空?
-
@Iliar Turdushev 这就是我想做的。但约束只能像
where T : notnull那样工作。我希望Create<T>方法根据T是否可以为空来抛出ArgumentNullException
标签: c# generics c#-8.0 nullable-reference-types