如何从 C# 中的泛型方法返回 NULL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/302096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:19:54  来源:igfitidea点击:

How can I return NULL from a generic method in C#?

c#generics

提问by edosoft

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

我有一个带有这个(虚拟)代码的通用方法(是的,我知道 IList 有谓词,但我的代码没有使用 IList 而是使用其他一些集合,无论如何这与问题无关......)

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

This gives me a build error

这给了我一个构建错误

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

“无法将 null 转换为类型参数 'T',因为它可能是值类型。请考虑使用 'default(T)'。”

Can I avoid this error?

我可以避免这个错误吗?

采纳答案by Jon Skeet

Two options:

两种选择:

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

回答by Ricardo Villamil

return default(T);

回答by Mitchel Sellers

Take the recommendation of the error... and either user default(T)or new T.

接受错误的建议...以及 userdefault(T)new T.

You will have to add in a comparison in your code to ensure that it was a valid match if you go that route.

您必须在代码中添加一个比较,以确保如果您走那条路线,它是一个有效的匹配项。

Otherwise, potentially consider an output parameter for "match found".

否则,可能会考虑“找到匹配项”的输出参数。

回答by BFree

Your other option would be to to add this to the end of your declaration:

您的另一种选择是将其添加到声明的末尾:

    where T : class
    where T: IList

That way it will allow you to return null.

这样它就可以让你返回 null。

回答by TheSoftwareJedi

You can just adjust your constraints:

你可以调整你的约束:

where T : class

Then returning null is allowed.

然后返回 null 是允许的。

回答by Min

Add the class constraint as the first constraint to your generic type.

将类约束作为第一个约束添加到泛型类型。

static T FindThing<T>(IList collection, int id) where T : class, IThing, new()

回答by devi

solution of TheSoftwareJedi works,

TheSoftwareJedi作品的解决方案,

also you can archive it with using couple of value and nullable types:

您也可以使用几个值和可为空类型来存档它:

static T? FindThing<T>(IList collection, int id) where T : struct, IThing
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return thing;
    }
    return null;
}

回答by devi

  1. If you have object then need to typecast

    return (T)(object)(employee);
    
  2. if you need to return null.

    return default(T);
    
  1. 如果您有对象,则需要进行类型转换

    return (T)(object)(employee);
    
  2. 如果您需要返回空值。

    return default(T);
    

回答by Luke

Here's a working example for Nullable Enum return values:

这是 Nullable Enum 返回值的工作示例:

public static TEnum? ParseOptional<TEnum>(this string value) where TEnum : struct
{
    return value == null ? (TEnum?)null : (TEnum) Enum.Parse(typeof(TEnum), value);
}

回答by Jaydeep Shil

Below are the two option you can use

以下是您可以使用的两个选项

return default(T);

or

或者

where T : class, IThing
 return null;