c# - 为什么不能将 null 转换为 C# 中的类型参数 T?

标签 c# vb.net vb.net-to-c#

我正在将一堆代码从 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/

相关文章:

c# - 对 Properties.Settings.Default 使用依赖注入(inject)?

vb.net - windows XP中如何设置默认编码?

asp.net - vb 中的数据列表。尝试获取数据列表中行或单元格的特定值

vb.net - SSIS包中的脚本任务到FTP

.net - 替代 C# 中 VB.NET 的类型转换函数 (CBool​​)?

c# - 将 VB.NET 转换为 C# 时出现问题

具有动态接口(interface)的 C# COM 对象

javascript - 单击几次后 ModalPopupExtender 不显示

c# - 将具有多个事件参数的 VB.NET 事件转换为 C#

c# - 为什么wpf控件只有一个命令? (MVVM)