我有一个带有这个(虚拟)代码的通用方法(是的,我知道 IList 有谓词,但我的代码没有使用 IList,而是使用其他一些集合,无论如何这与问题无关......)
static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
foreach (T thing in collection)
{
if (thing.Id == id)
return thing;
}
return null; // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
}
这给我一个构建错误
"Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead."
我可以避免这个错误吗?
最佳答案
三个选项:
- 返回
default
(或default(T)
用于旧版本的 C#),这意味着如果T,您将返回
是引用类型(或可空值类型),null
0
为int
,'\0'
为char
等 ( Default values table (C# Reference) ) - 如果您愿意使用
where T : class
约束将T
限制为引用类型,然后照常返回null
- 如果您乐于使用
where T : struct
约束将T
限制为不可空值类型,那么您可以再次返回null
与返回值T?
的方法一样正常 - 请注意,这不是返回 null 引用,而是可为 null 值类型的 null 值.
关于c# - 如何从 C# 中的泛型方法返回 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/302096/