我正在将一堆代码从 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 返回 Nothing(null)。
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;
}
它不会编译并出现此错误:
The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method
'System.Nullable<T>'
我需要能够具有相同的功能,否则会破坏很多代码。我错过了什么?
最佳答案
由于T
可以是引用类型或值类型,因此如果T是值类型,则返回null
将不满足。您应该返回:
return default(T);
来自链接default keyword :
Given a variable t of a parameterized type T, the statement t = null is only valid if T is a reference type and t = 0 will only work for numeric value types but not for structs. The solution is to use the default keyword, which will return null for reference types and zero for numeric value types. For structs, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types. For nullable value types, default returns a System.Nullable, which is initialized like any struct.
更新 (2021-09-27)
使用 C# 7.1 中的新语法,您可以返回:
return default;
关于c# - 为什么不能将 null 转换为 C# 中的类型参数 T?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28133205/