如何从 C# 中的泛型方法返回 NULL? [英] How can I return NULL from a generic method in C#?

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

问题描述

我有一个带有这个(虚拟)代码的通用方法(是的,我知道 IList 有谓词,但我的代码没有使用 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.
}

这给了我一个构建错误

"无法将空值转换为类型参数'T' 因为它可能是一个值类型.考虑改用'default(T)'."

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

我可以避免这个错误吗?

Can I avoid this error?

推荐答案

两个选项:

  • 返回 default(T) 这意味着如果 T 是引用类型(或可空值类型),则返回 null0 用于 int'' 用于 char 等(默认值表(C# 参考))
  • 将 T 限制为具有 where T : class 约束的引用类型,然后正常返回 null
  • Return default(T) which means you'll return null if T is a reference type (or a nullable value type), 0 for int, '' for char, etc. (Default values table (C# Reference))
  • Restrict T to be a reference type with the where T : class constraint and then return null as normal

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

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