2012-07-29 90 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

通用約束不影響超載結果。當你省略第二個參數時,編譯器很難確定發生了什麼。

相關問題