我有下一堂课:
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);
}
}
出现此错误的原因是什么?
答案 0 :(得分:1)
为了重载方法,参数必须是不同的类型,否则必须有不同数量的参数。在您的示例中:
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> o
和this TInput o
答案 1 :(得分:0)
在第一个代码中,您具有相同的参数类型(此TInput o,Func评估程序)。