3

次の関数を呼び出す必要があります:

static string GetValueOrDefault(object[] values, int index)
{
    if (values == null)
         return string.Empty;
    if (index >= values.Length)
         return string.Empty;
    return values[index] != null ? values[index].ToString() : string.Empty;
}

文字列の配列(ReferenceType)を使用してGetValueOrDefaultを呼び出すと、次のように機能します。

GetValueOrDefault(new[] {"foo", "bar"}, 0);

int(ValueType)の配列を使用してGetValueOrDefaultを呼び出すと、機能しません:

GetValueOrDefault(new[] {1, 2}, 0);

コンパイラエラーは次のとおりです。

MyNamespace.GetValueOrDefault(object []、int)'に最適なオーバーロードされたメソッドの一致には、いくつかの無効な引数があります

だから私の質問は:なぜこれは参照型と値型がオブジェクトから派生するのでコンパイルされないのですか?

ジェネリックを使用してこの問題を解決できることはわかっていますが、このエラーを理解したい

static string GetValueOrDefault<T>(T[] values, int index)
{...}

前もって感謝します

4

1 に答える 1

6

Arrays of reference-types are covariant, meaning: a string[] can be treated as an object[] (although the gotcha is that if you try to put a non-string in, it will throw). However, arrays of value-types are not covariant, so an int[] cannot be treated as an object[]. new[] {1,2} is an int[].

IIRC this was done mainly for similarity with java. The covariance in .NET 4.0 is much tidier.

于 2013-01-29T12:45:19.737 に答える