2016-07-29 35 views
0

有谁知道为什么我不能使用Linq扩展方法Cast<>()Int转换为UInt意外`指定的演员表无效.`````例外(Linq)

var myIntList = new List<int>(); 

myIntList.Add(1); 
myIntList.Add(2); 
myIntList.Add(3); 

var myUIntList = myIntList.Cast<uint>().ToList(); 

它抛出一个指定的转换是无效。当我使用Select()时,它将工作(ofcourse)

var myIntList = new List<int>(); 

myIntList.Add(1); 
myIntList.Add(2); 
myIntList.Add(3); 

var myUIntList = myIntList.Select(i => (uint)i).ToList(); 

(它是一个错误或不实现功能?)

回答

4

Enumerable.Cast实现为运行在IEnumerable的扩展方法(非通用接口)。

这意味着这个序列中的值是从object开始的,这意味着值类型会涉及装箱和拆箱。您只能取消确切的类型。例如:

int i = 1; 
object boxed = i; 

int unboxToInt = (int)boxed; // ok 
uint unboxToUint = (uint)boxed; // invalid cast exception 

你可以阅读更多关于拳击in the documentation

+0

这一切都清楚。我会做一些阅读。 –