如何解决T?,C# 9 中可为空的类型参数
This program 有两个错误:
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");
T?
必须是可空类型。不过好像上面程序中的T?
和T
是一样的。
?
中是否忽略了 T?
?
编辑:带有struct
约束的Both errors disappear:
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");
我不明白为什么约束会改变结果。
解决方法
当您在 T?
和 T?
中说 (T? t)
时,它们都指的是可为空的引用类型,而不指的是特殊的 Nullable<T>
结构.您无法指定泛型参数,以便将其视为类和可为空的值类型。
第二个错误只是因为 f(10)
(所以 f<int>(10)
)被隐式地视为 int
(因为没有可空引用 int 值这样的东西),所以 {{1 }} 无效,就像您执行 null
一样。
如果 if (10 is null)
停止打开,而是添加了诸如 T
之类的约束,where T : struct
将变为 T?
而不是可空引用参数,因此代码变为与引入可为空引用类型之前完全相同。
我不知道第一个错误,但第二个。
f(10) is null
被推断为 int
代替 int?
,因为 10
是 int
类型。
应使用 f((int?)10) is null
或 f<int?>(10) is null
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。