我有一个通用方法,其代码如下(是的,我知道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.
}
我遇到了一个构建错误
"不能将null转换为类型参数'T',因为它可能是值类型。考虑使用'default(T)'代替。"
我能避免这个错误吗?
T
是Object
还是int
或char
,都返回null
。 - AlexanderT?
无法工作。@Alexander-ReinstateMonica 我已经阅读了文章,但无论是引用类型还是值类型,我都找不到返回null
的方法。 - mireazmanull
作为某些地方出现问题的指示。我建议改为抛出异常。这就是异常存在的原因,你可以省略在每个地方编写if (... != null)
的步骤。 - Markus Safar