Answers:
采用以下通用方法:
public static T Get<T>(T value)
{
return value;
}
如果我们将其命名为Get<string>(s)
,则返回值是不可为null的,而如果这样做Get<string?>(s)
,则它将为可为null的。
但是,如果您使用诸如Get<T>(x)
和的通用参数来调用它,并且T
无法解析,例如,它是您的通用类的通用参数,如下所示...
class MyClass<T>
{
void Method(T x)
{
var result = Get<T>(x);
// is result nullable or non-nullable? It depends on T
}
}
在这里,编译器不知道最终是否会使用可为null或不可为null的类型来调用它。
我们可以使用一种新的类型约束来表示T
不能为空:
public static T Get<T>(T value) where T: notnull
{
return value;
}
但是,在T
不受约束且仍然开放的地方,可为空性是未知的。
如果将这些未知数视为可为空,则可以编写以下代码:
class MyClass<T>
{
void Method(T x)
{
var result = Get<T>(x);
// reassign result to null, cause we we could if unknown was treated as nullable
result = null;
}
}
在T
不可为空的情况下,我们应该得到警告。因此,对于未知的可空性类型,我们在取消引用时需要警告,但也可能需要潜在的分配警告null
。