我尝试这样做:
IEnumerable<object> ids = new List<string>() { "0001", "0002", "0003" };
效果很好!
但是当我尝试这样做时:
IEnumerable<object> intIds = new List<System.Int32>() { 1, 2, 3 };
Visual Studio 告诉我:
无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(您是否缺少类型转换?)
为什么?
最佳答案
int
是值类型,只能装箱到object
- 它不是从 object
继承的.由于您使用的是 IEnumerable<object>
无论如何,这应该有效:
IEnumerable intIds = new List<int>() { 1, 2, 3 };
关于.net-4.0 - 为什么我不能在 .NET 4.0 中将 List<int> 分配给 IEnumerable<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8175311/