2012-07-29 89 views
3

我得到这些扩展:为什么扩展方法调用不明确?

internal static TResult With<TInput, TResult> 
    (this TInput? o, Func<TInput, TResult> selector, TResult defaultResult = null) 
    where TInput : struct 
    where TResult : class 
{ 
    selector.ThrowIfNull("selector"); 
    return o.HasValue ? selector(o.Value) : defaultResult; 
} 
internal static TResult? With<TInput, TResult> 
    (this TInput? o, Func<TInput, TResult> selector, TResult? defaultResult = null) 
    where TInput : struct 
    where TResult : struct 
{ 
    selector.ThrowIfNull("selector"); 
    return o.HasValue ? selector(o.Value) : defaultResult; 
} 

第一个是在参考输入结果和上一个结构的可空的第二个取向。

那么现在为什么在第一行我得到编译错误,第二我没有?

1.

TimeSpan? time = ((int?)4).With(T => TimeSpan.FromSeconds(T)) 
// Error. The call is ambiguous. 

2.

TimeSpan? time = ((int?)4).With(T => TimeSpan.FromSeconds(T), null) 
// No errors. Normally calls the second extension. 

是不是obvius该时间跨度(作为TResult)是一个结构,这是在每个延伸的最顶部规定?

回答

0

钍原因,你得到的第一个错误,因为返回类型不是可空和你投4为可空INT

int? time = ((int?)4).With(T => TimeSpan.FromSeconds(T)) 
// Error. The call is ambiguous. 
+0

删除答案我解决了问题 – AgentFire 2012-07-29 16:45:51

+0

@AgentFire我已经得到-1,然后再纠正你的问题 – HatSoft 2012-07-29 16:47:26

+0

那不是我! – AgentFire 2012-07-29 16:47:47

0

因为return typeconstraints不是方法签名的一部分。

0

通用约束不影响超载结果。当你省略第二个参数时,编译器很难确定发生了什么。

相关问题