我正在将一堆代码从VB转换到C#,我正在处理一个方法的问题。这个VB方法工作得很好:
Public Function FindItem(ByVal p_propertyName As String, ByVal p_value As Object) As T
Dim index As Int32
index = FindIndex(p_propertyName, p_value)
If index >= 0 Then
Return Me(index)
End If
Return Nothing
End Function它允许对T返回空(空)。
C#等价物不起作用:
public T FindItem(string p_propertyName, object p_value)
{
Int32 index = FindIndex(p_propertyName, p_value);
if (index >= 0) {
return this[index];
}
return null;
}它不会使用以下错误进行编译:
类型'T‘必须是非空值类型,才能将其用作泛型类型或方法
'System.Nullable<T>'中的参数'T’。
我需要能够拥有相同的功能,否则它会破坏很多代码。我遗漏了什么?
发布于 2015-01-25 04:34:48
因为T可以是引用类型,也可以是值类型,所以如果T是值类型,返回null就不能满足。你应该返回:
return default(T);从链接默认关键字
给定参数化类型T的变量T,只有当T是引用类型时,t= null语句才有效,并且t=0只适用于数值类型,而不适用于结构。解决方案是使用默认关键字,对于引用类型返回null,对于数值类型返回零。对于结构,它将返回初始化为零或空的结构的每个成员,这取决于它们是值类型还是引用类型。对于可空值类型,default返回一个System.Nullable,它与任何结构一样被初始化。
更新(2021-09-27)
使用C# 7.1中的新语法,您可以返回:
return default;https://stackoverflow.com/questions/28133205
复制相似问题