可能重複:
Enumerable.Cast<T> extension method fails to cast from int to long, why ?
Puzzling Enumerable.Cast InvalidCastException
Cast/Convert IEnumerable<T> to IEnumerable<U> ?爲什麼不會投入<double>()在IEnumerable <int>上工作?
我試圖整數數組轉換成double數組(這樣我就可以把它傳遞給需要的功能雙打數組)。
最明顯的解決方案(對我來說,至少)是對IEnumerable使用Cast擴展函數,但它給了我一個InvalidCastException,我不明白爲什麼。我的解決方法是使用Select,但我認爲Cast看起來更整潔。
有人能告訴我爲什麼Cast方法不起作用嗎?
希望下面的代碼說明了我的問題:
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()));
}
}
}
Ooops ...在詢問之前,我沒有仔細檢查堆棧溢出情況。我發現我的問題已被問及並回答:http://stackoverflow.com/questions/1684448/enumerable-castt-extension-method-fails-to-cast-from-int-to-long-why – dominic 2009-12-08 06:46:09