これらの拡張機能を取得しました:
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;
}
最初のものは参照型の結果に向けられ、2 つ目は構造体の Nullable に向けられています。
では、なぜ最初の行でコンパイル エラーが発生し、2 行目では発生しないのでしょうか。
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.
TimeSpan (としてTResult
) が構造体であり、各拡張機能の最上部で指定されていることは明らかではありませんか?