我怎样才能返回NULL从C#泛型方法? [英] How can I return NULL from a generic method in C#?

查看:767
本文介绍了我怎样才能返回NULL从C#泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个(虚拟)code通用的方法(是的,我知道的IList有predicates,但我的code未使用的IList但一些其他集合,反正这是无关这个问题...)

I have a generic method with this (dummy) code (yes I'm aware IList has predicates, but my code is not using IList but some other collection, anyway this is irrelevant for the question...)

static T FindThing<T>(IList collection, int id) where T : IThing, new()
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;  // ERROR: Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead.
}

这给了我一个生成错误

无法将null转换为类型参数
  T,因为它可能是一个值类型。
  考虑使用默认(T),而不是

"Cannot convert null to type parameter 'T' because it could be a value type. Consider using 'default(T)' instead."

我能避免这个错误?

推荐答案

有两种选择:


  • 返回默认(T)这意味着你将返回如果T是引用类型(或对于焦炭等
  • 空值类型),0对于int,'\\ 0'
  • 限制T可为引用类型与其中T:类约束,然后正常返回null

  • Return default(T) which means you'll return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char etc
  • Restrict T to be a reference type with the where T : class constraint and then return null as normal

这篇关于我怎样才能返回NULL从C#泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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