扩展歧义错误

本文关键字:错误 歧义 扩展 | 更新日期: 2023-09-27 17:50:53

我有下一节课:

public static class Monads
{
    public static TResult With<TInput, TResult>
        (this TInput o, Func<TInput, TResult> evaluator)
        where TInput: class
        where TResult: class
    {
        if (o == null) return null;
        return evaluator(o);
    }
    public static Nullable<TResult> With<TInput, TResult>
        (this TInput o, Func<TInput, TResult> evaluator)
        where TInput : class
        where TResult : struct
    {
        if (o == null) return null;
        return evaluator(o);
    }
}

当我尝试使用它时,我得到了一个错误:"错误以下方法或属性之间的调用有歧义:'CoreLib.Monads.With<TInput,TResult>(TInput, System.Func<TInput,TResult>)''CoreLib.Monads.With<TInput,TResult>(TInput, System.Func<TInput,TResult>)' "

但是这个方法不同于类型的约束和Nullable是一个结构体。然而,这段代码工作得很好:

public static class Monads
{
    public static TResult Return<TInput, TResult>
        (this TInput o, Func<TInput, TResult> evaluator,
        TResult failureValue)
        where TInput: class
    {
        if (o == null) return failureValue;
        return evaluator(o);
    }

    public static TResult Return<TInput, TResult>
        (this Nullable<TInput> o, Func<TInput, TResult> evaluator,
        TResult failureValue)
        where TInput : struct
    {
        if (!o.HasValue) return failureValue;
        return evaluator(o.Value);
    }
}

这个错误的原因是什么?

扩展歧义错误

为了重载方法,要么参数必须是不同的类型,要么必须有不同数量的参数。在您的示例中:

public static TResult With<TInput, TResult>
    (this TInput o, Func<TInput, TResult> evaluator)         
public static Nullable<TResult> With<TInput, TResult>
    (this TInput o, Func<TInput, TResult> evaluator)

可以看到参数是完全相同的。第二个例子可以工作,因为您正在为this Nullable<TInput> othis TInput o这两种不同类型的对象编写扩展方法

在第一个代码中,您有相同的参数类型(这个TInput o, Func求值器)。