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;
}

最初のものは参照型の結果に向けられ、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) が構造体であり、各拡張機能の最上部で指定されていることは明らかではありませんか?

4

4 に答える 4

2

制約は署名の一部ではないためです。

于 2012-07-29T16:44:59.587 に答える
0

戻り値の型が Nullable ではなく、4 を nullable int にキャストするため、最初のエラーが発生する理由

int? time = ((int?)4).With(T => TimeSpan.FromSeconds(T))
// Error. The call is ambiguous.
于 2012-07-29T16:43:23.220 に答える
0

return typeconstraintsはメソッド シグネチャの一部ではないためです。

于 2012-07-29T16:45:51.693 に答える
0

一般的な制約はオーバーロードの結果に影響しません。また、2 番目のパラメーターを省略すると、コンパイラーは何が起こるかを判断するのに苦労します。

于 2012-07-29T16:47:57.470 に答える