我隔壁班:Extensiong明確的錯誤
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是struct。 但是,此代碼工作正常:
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);
}
}
什麼原因這個錯誤的?