嗨
我使用通用的,可为空的有这样的代码:泛型类型参数和可空方法重载
// 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