假设我们有一些带有 2 个参数的通用方法:
private void TestConstraints<TKey>(TKey key, TKey? nullableKey)
where TKey : notnull { }
Run Code Online (Sandbox Code Playgroud)
从 .NET6 的角度来看,这完全没问题,因为没有添加可为空的引用类型。但使用尝试失败,原因是 CS8714 类型不能用作参数:
private void TestMethod()
{
var id = 5;
int? nullableId = null;
TestConstraints(id, nullableId);
}
Run Code Online (Sandbox Code Playgroud)
警告 CS8714 类型“int?” 不能用作泛型类型或方法“TestClass.TestConstraints(TKey, TKey?)”中的类型参数“TKey”。类型参数“int”的可空性?与“notnull”约束不匹配。
明确指定类型 asint没有帮助。
有人可以澄清我是否可以这样操作(将输入参数定义为TKey?),以及文档中的说明位置吗?
编译器版本:
Microsoft (R) 构建引擎版本 17.2.0+41abc5629