我有一个通用的方法与这个(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)’。”

我能避免这个错误吗?


当前回答

这里有一个Nullable Enum返回值的工作示例:

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

其他回答

return default(T);

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

return default(T);

or

where T : class, IThing
 return null;

上述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()

这里有一个Nullable Enum返回值的工作示例:

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