T?,C# 9 中可为空的类型参数

use*_*077 5 c# nullable c#-9.0

这个程序有两个错误:

using System;

T? f<T>(T? t)
{    
    t = null; //  Error CS0403  Cannot convert null to type parameter 'T' because it could be a non-nullable value type
    return default(T?);
}

if(f(10) is null) // Error  CS0037  Cannot convert null to 'int' because it is a non-nullable value type    
    Console.WriteLine("null");
Run Code Online (Sandbox Code Playgroud)

T?必须是可空类型。不过好像和上面的程序T?是一样的T

?忽略T?


编辑两个错误都会随着struct约束消失

using System;

T? f<T>(T? t)  where T : struct
{    
    t = null; // error
    return default(T?);
}

if(f<int>(10) is null) // error
    Console.WriteLine("null");
Run Code Online (Sandbox Code Playgroud)

我不明白为什么约束会改变结果。

SO *_*ood 7

当您说T?inT?和 in 时(T? t),它们都指的是可为空的引用类型,而不是特殊的Nullable<T>结构。您无法指定泛型参数,以便将其视为类和可为空值类型。

第二个错误只是因为f(10)(so f<int>(10)) 被隐式地视为 an int(因为不存在可空引用 int 值之类的东西),所以null无效,就像您所做的那样if (10 is null)


如果T停止打开,而是添加一个约束,例如where T : struct, ,而T?不是System.Nullable<T>可空引用参数,因此代码变得与引入可空引用类型之前完全相同。