Bản sao có thể xảy ra:
Enumerable.Cast<T> extension method fails to cast from int to long, why ?
Puzzling Enumerable.Cast InvalidCastException
Cast/Convert IEnumerable<T> to IEnumerable<U> ?Tại sao không Cast <double>() hoạt động trên IEnumerable <int>?
Tôi đang cố gắng để chuyển đổi một mảng các số nguyên để một loạt các đôi (vì vậy tôi có thể vượt qua nó để một hàm mang theo một mảng đôi).
Giải pháp rõ ràng nhất (với tôi, ít nhất) là sử dụng chức năng mở rộng Cast cho IEnumerable, nhưng nó mang lại cho tôi một InvalidCastException và tôi không hiểu tại sao. Giải pháp thay thế của tôi là sử dụng Chọn thay thế, nhưng tôi nghĩ Cast trông có vẻ nấp.
Ai đó có thể cho tôi biết tại sao phương thức Truyền không hoạt động?
Hy vọng rằng các mã dưới đây minh họa vấn đề của tôi:
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()));
}
}
}
Rất tiếc ... Tôi không kiểm tra tràn ngăn xếp cẩn thận trước khi yêu cầu. Tôi đã tìm thấy câu hỏi của mình đã được yêu cầu và trả lời: http://stackoverflow.com/questions/1684448/enumerable-castt-extension-method-fails-to-cast-from-int-to-long-why – dominic