可能显示的文件: Enumerable.Cast<T>扩展方法不能投从int长,为什么呢? Puzzling Enumerable.Cast InvalidCastException的 Cast/Convert IEnumerable的&LT; T&GT;到了IEnumerable&LT; U&GT; ?
Possible Duplicates: 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数组(这样我就可以把它传递给一个函数,它双打的数组)。
I'm trying to convert an array of integers to an array of doubles (so I can pass it to a function that takes an array of doubles).
最明显的解决方案(对我来说,至少)是使用Cast扩展功能IEnumerable的,但它给了我一个InvalidCastException,我不明白为什么。我的解决方法是使用选择,而不是,但我认为演员看起来更加整洁。
The most obvious solution (to me, at least) is to use the Cast extension function for IEnumerable, but it gives me an InvalidCastException, and I don't understand why. My workaround is to use Select instead, but I think Cast looks neater.
有人能告诉我,为什么铸造法是不工作?
Could someone tell me why the Cast method isn't working?
但愿code以下说明我的问题:
Hopefully the code below illustrates my problem:
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()));
}
}
}
推荐答案
这个问题是来自投运营商(重载)的事实,在编译时解决。 试想想怎样投实现。我敢打赌,code是这样的:
The problem comes from the fact that cast operators (overloaded) are resolved at compile time. Try to think how Cast is implemented. I bet the code looks like this:
public static IEnumerable<T> Cast<T>(this IEnumerable source)
{
foreach(object element in source)
{
yield return (T)element;
}
}
所有的编译器的信息是,它需要对象转换为T类型而对于它会使用默认的继承铸造。没有自定义重载运算符将被使用。而在你的榜样一个int是不是双这样的演员会失败。
All the info the compiler has is that it needs to cast an object to a type T. And for that it will use the default inheritance casting. No custom overloaded operator will be used. And in your example an int is not a double so the cast will fail.
在选择例如:
source.Select(a => (double)a));
工作,因为编译器知道这两种类型,它是能够调用相应的重载运算符。
works because the compiler knows both types and it's able to call the appropriate overloaded operator.
相关推荐
最新文章