generics类型参数和Nullable方法重载
你好
我有使用generics和可空的代码:
// The first one is for class public static TResult With(this TInput o, Func evaluator) where TResult : class where TInput : class // The second one is for struct (Nullable) public static TResult With(this Nullable o, Func evaluator) where TResult : class where TInput : struct
请注意TInput约束,一个是类,另一个是struct。 然后我用它们:
string s; int? i; // ... s.With(o => ""); i.With(o => ""); // Ambiguos method
它会导致Ambiguos错误。 但我还有另一对:
public static TResult Return(this TInput o, Func evaluator, TResult failureValue) where TInput : class public static TResult Return(this Nullable o, Func evaluator, TResult failureValue) where TInput : struct
这个编译成功
string s; int? i; // ... s.Return(o => 1, 0); i.Return(o => i + 1, 0);
我没有找到为什么会发生这种情况的线索。 第一个看起来好,但编译错误。 第二个(’Return’)如果是第一个,则应该是错误,但是成功编译。 我错过了什么?
选择过载时不考虑generics方法中的约束 – 在选择过载后检查它们。
作为选择过载的一部分,检查参数类型中的约束。 这有点令人困惑,但最终有意义。
我有一篇关于此的博文可能有助于进一步理解它。
另外请注意,您的第二个示例具有有助于类型推断的附加参数,这是两者之间的区别。 TResult
被推断为int
,它阻止第一个重载有效 – 没有从(int? x) => x + 1
到Func
的转换,而从(int x) => x + 1
转换(int x) => x + 1
到Func
。