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

我能避免这个错误吗?


当前回答

解决方案的软件绝地作品,

你也可以使用一对value和nullable类型来存档:

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

其他回答

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

return default(T);

or

where T : class, IThing
 return null;

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

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

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

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

你可以调整你的约束条件:

where T : class

然后返回null是允许的。

你的另一个选择是在你的声明后面加上这个:

    where T : class
    where T: IList

这样它将允许您返回null。