加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:45:25 所属栏目:百科 来源:网络整理
导读:我正在将一堆代码从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 Th
我正在将一堆代码从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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读