嗨
我使用通用的,可爲空的有這樣的代碼:泛型類型參數和可空方法重載
// The first one is for class
public static TResult With<TInput, TResult>(this TInput o,
Func<TInput, TResult> evaluator)
where TResult : class
where TInput : class
// The second one is for struct (Nullable)
public static TResult With<TInput, TResult>(this Nullable<TInput> o,
Func<TInput, TResult> evaluator)
where TResult : class
where TInput : struct
請注意TInput約束,一個是類,另一種是結構。然後我使用它們:
string s;
int? i;
// ...
s.With(o => "");
i.With(o => ""); // Ambiguos method
它會導致Ambiguos錯誤。但我也有另一對:
public static TResult Return<TInput, TResult>(this TInput o,
Func<TInput, TResult> evaluator, TResult failureValue)
where TInput : class
public static TResult Return<TInput, TResult>(this Nullable<TInput> o,
Func<TInput, TResult> evaluator, TResult failureValue)
where TInput : struct
這一個成功編譯
string s;
int? i;
// ...
s.Return(o => 1, 0);
i.Return(o => i + 1, 0);
我沒有線索,爲什麼發生這種情況。第一個看起來不錯,但編譯錯誤。第二個('Return')應該是錯誤的,如果第一個是,但是編譯成功。我錯過了什麼?泛型方法中
就像一個樣式註釋,我會避免使用lambda參數的相同名稱作爲範圍內的變量。 – 2011-04-28 07:19:51
啊對,那實際上會導致編譯錯誤。我只是匆匆粘貼和編輯代碼。 – 2011-04-28 07:26:37