use*_*079 9 c# ienumerable list icomparable
我可以隐式地将一个int转换为IComparable.我也可以将一个List或一个数组转换为IEnumerable.
但为什么我不能隐式地将List转换为IEnumerable?
我用.net framework 4.5和Visual Studio 2012 Ultimate测试了这个.
要测试的代码:
IComparable test1;
int t1 = 5;
test1 = t1; //OK
IEnumerable<int> test2;
List<int> t2 = new List<int>();
int[] t3 = new int[] { 5, 6 };
test2 = t2; //OK
test2 = t3; //OK
TabAlignment[] test;
IEnumerable<IComparable> test3;
test3 = t2; //error Cannot implicitly convert type 'System.Collections.Generic.List<int>' to 'System.Collections.Generic.IEnumerable<System.IComparable>'. An explicit conversion exists (are you missing a cast?)
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 13
基本上,通用方差不适用于值类型.所以尽管你可以
你需要打包每个值:
IEnumerable<IComparable> test3 = t2.Cast<IComparable>();
Run Code Online (Sandbox Code Playgroud)
所以虽然这是有效的,因为它string是一个引用类型:
List<string> strings = new List<string>();
IEnumerable<IComparable> comparables = strings;
Run Code Online (Sandbox Code Playgroud)
......相当于不起作用List<int>,你需要随身携带.
| 归档时间: |
|
| 查看次数: |
3452 次 |
| 最近记录: |