为什么不能在C#中将null转换为类型T的参数? [英] Why cannot convert null to type parameter T in c#?

查看:66
本文介绍了为什么不能在C#中将null转换为类型T的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一堆代码从VB转换为C#,并且遇到了方法问题.这种VB方法效果很好:

I'm converting a bunch of code from VB to C# and I'm running in to an issue with a method. This VB method works great:

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).

It allow the return of Nothing(null) for T.

C#等效项不起作用:

The C# equivalent does not work:

public T FindItem(string p_propertyName, object p_value)
{
  Int32 index = FindIndex(p_propertyName, p_value);

  if (index >= 0) {
    return this[index];
  }
  return null;
}

它不会编译并显示此错误:

It won't compile with this error:

类型"T"必须为非空值类型,才能在通用类型或方法'System.Nullable< T>'

我需要能够具有相同的功能,否则它将破坏很多代码.我想念什么?

I need to be able to have the same functionality or it will break a lot of code. What am I missing?

推荐答案

由于 T 可以是引用类型或值类型,因此如果T不能返回 null 是值类型.您应该返回:

Since T can be either reference type or value type, so returning null will not satisfy if T is value type. You should return:

return default(T);

从链接默认关键字:

给定参数化类型T的变量t,仅当T为引用类型且t = 0仅适用于数值类型而不适用于结构体时,语句t = null才有效.解决方案是使用默认关键字,对于引用类型,该关键字将返回null,对于数值类型,将返回零.对于结构,它将返回初始化为零或null的结构的每个成员,具体取决于它们是值类型还是引用类型.对于可为null的值类型,默认返回System.Nullable,该System.Nullable像任何结构一样被初始化.

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.

这篇关于为什么不能在C#中将null转换为类型T的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆