2015-05-26 29 views
-1

我隔壁班: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); 
    } 
} 

什麼原因這個錯誤的?

回答

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> othis TInput o

0

在第一個代碼中,您具有相同的參數類型(此TInput o,Func評估器)。