为什么是T?不是可空类型吗?

Wei*_*ieh 7 c#

为什么下面的代码不起作用?

public T? Method<T>() 
{
    /*
     error CS0403: Cannot convert null to type parameter 'T' 
     because it could be a non-nullable value type.
     Consider using 'default(T)' instead.
    */
    return null;
}
Run Code Online (Sandbox Code Playgroud)

Ill*_*ian 7

为了向后兼容,T?被实现为纯编译时构造。对于引用类型,与运行时相同T。对于值类型,它被转换为Nullable<T>. T编译器需要在编译时确定这是一个值类型才能进行转换。因此,对于无约束类型T,编译器不能假设T?可以为空。

要获得 OP 中的行为,唯一的 OOTB 方法似乎是重载引用和值类型的方法。不幸的是,更改类型约束不足以进行重载解析,因此名称或参数也需要不同。

public static T? Method<T>() where T : struct
{
    return null;
}

public static T Method<T>(int placeholder = 0) where T : class
{
    return null;
}
Run Code Online (Sandbox Code Playgroud)

根据您想要执行的操作,Chenga 的解决方案可能更容易使用,但如果您绝对需要它返回带有不可为空类型约束的 null ,那么这将起作用。如果您担心default成为非空值,您还可以实现一种Optional类型,例如链接问题中的类型,然后返回该类型而不是T.