我有一个通用的方法与这个(虚拟)代码(是的我知道IList有谓词,但我的代码不使用IList但其他一些集合,无论如何这与问题无关...)
static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
foreach T thing in collecion
{
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.
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个构建错误
"无法将null转换为类型参数'T',因为它可能是值类型.请考虑使用'default(T)'."
我可以避免这个错误吗?
Jon*_*eet 928
两种选择:
default(T)
表示null
如果T是引用类型(或可空值类型),0
for int
,'\0'
for char
等,则返回(默认值表(C#Reference))where T : class
约束的引用类型,然后null
正常返回Ric*_*mil 78
return default(T);
Run Code Online (Sandbox Code Playgroud)
Min*_*Min 12
将类约束添加为泛型类型的第一个约束.
static T FindThing<T>(IList collection, int id) where T : class, IThing, new()
Run Code Online (Sandbox Code Playgroud)
小智 7
如果你有对象则需要进行类型转换
return (T)(object)(employee);
Run Code Online (Sandbox Code Playgroud)如果你需要返回null.
return default(T);
Run Code Online (Sandbox Code Playgroud)以下是您可以使用的两个选项
return default(T);
Run Code Online (Sandbox Code Playgroud)
要么
where T : class, IThing
return null;
Run Code Online (Sandbox Code Playgroud)
您的另一个选择是将此添加到您的声明的末尾:
where T : class
where T: IList
Run Code Online (Sandbox Code Playgroud)
这样它将允许您返回null.
为了完整起见,很高兴知道您也可以这样做:
return default;
Run Code Online (Sandbox Code Playgroud)
它返回的结果与return default(T);
TheSoftwareJedi作品的解决方案,
您也可以使用几个值和可为空类型来存档它:
static T? FindThing<T>(IList collection, int id) where T : struct, IThing
{
foreach T thing in collecion
{
if (thing.Id == id)
return thing;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
165361 次 |
最近记录: |