가능한 중복 :
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에 대한 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 ... 묻기 전에 Stack overflow를 충분히 신중하게 확인하지 않았습니다. 내 질문에 이미 물어 답변 : http://stackoverflow.com/questions/1684448/enumerable-castt-extension-method-fails-to-cast-from-int-to-long-why – dominic