【发布时间】:2023-03-31 21:05:01
【问题描述】:
嗨
我使用通用和可为空的代码:
// 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 参数使用与已经在范围内的变量相同的名称。
-
啊对,这实际上会导致编译错误。我只是匆忙粘贴和编辑代码。
标签: c# .net generics types nullable