我有一个通用的方法与这个(dummy)代码(是的,我知道IList有谓词,但我的代码不是使用IList而是一些其他的集合,无论如何这是无关紧要的问题…)

    static T FindThing<T>(IList collection, int id) where T : IThing, new()
    {
        foreach (T thing in collection)
        {
            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转换为类型参数 因为它可以是一个值类型。 考虑使用‘default(T)’。”

我能避免这个错误吗?


当前回答

上述2个答案的另一种选择。如果将返回类型更改为object,则可以返回null,同时转换非null返回。

static object FindThing<T>(IList collection, int id)
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return (T) thing;
    }
    return null;  // allowed now
}

其他回答

如果你有对象,那么需要类型转换 返回(T)(对象)(员工); 如果需要返回null。 返回默认值(T);

三个选项:

Return default (or default(T) for older versions of C#) which means you'll return null if T is a reference type (or a nullable value type), 0 for int, '\0' for char, etc. (Default values table (C# Reference)) If you're happy to restrict T to be a reference type with the where T : class constraint and then return null as normal If you're happy to restrict T to be a non-nullable value type with the where T : struct constraint, then again you can return null as normal from a method with a return value of T? - note that this is not returning a null reference, but the null value of the nullable value type.

上述2个答案的另一种选择。如果将返回类型更改为object,则可以返回null,同时转换非null返回。

static object FindThing<T>(IList collection, int id)
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return (T) thing;
    }
    return null;  // allowed now
}

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

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

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

return default(T);

or

where T : class, IThing
 return null;