在启用了可为空的 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)