重複の可能性:
Enumerable.Cast<T> extension method fails to cast from int to long, why ?
Puzzling Enumerable.Cast InvalidCastException
Cast/Convert IEnumerable<T> to IEnumerable<U> ?()がIEnumerable <int>で動作しないのはなぜですか?
私はdoubleの配列に整数の配列を変換しようとしている(私は取る関数に渡すことができます二重の配列)。
最も明白な解決策(少なくとも私にとっては)は、IEnumerableのキャスト拡張機能を使用することですが、それは私にInvalidCastExceptionを与えます。理由はわかりません。私の回避策はSelectを代わりに使用することですが、キャストはきれいに見えます。
キャスト方式が機能しない理由を教えてもらえますか?
うまくいけば、以下のコードは、私の問題を示す:
namespace ConsoleApplication1
{
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var intArray = new[] { 1, 2, 3, 4 };
PrintEnumerable(intArray, "intArray: ");
var doubleArrayWorks = intArray.Select(x => (double)x).ToArray();
PrintEnumerable(doubleArrayWorks, "doubleArrayWorks: ");
// Why does this fail??
var doubleArrayDoesntWork = intArray.Cast<double>().ToArray();
PrintEnumerable(doubleArrayDoesntWork, "doubleArrayDoesntWork: ");
// Pause
Console.ReadLine();
}
private static void PrintEnumerable<T>(
IEnumerable<T> toBePrinted, string msgPrefix)
{
Console.WriteLine(
msgPrefix + string.Join(
",", toBePrinted.Select(x => x.ToString()).ToArray()));
}
}
}
私は質問する前に十分に慎重にStack Overflowをチェックしませんでした。私は私の質問が既に尋ねられ、答えられていることが分かった:http://stackoverflow.com/questions/1684448/enumerable-castt-extension-method-fails-to-cast-from-int-to-long-why – dominic