为什么我不能分配List< int>到IEnumerable< object>在.NET 4.0中 [英] Why can't I assign List<int> to IEnumerable<object> in .NET 4.0

查看:87
本文介绍了为什么我不能分配List< int>到IEnumerable< object>在.NET 4.0中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试这样做:

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'。存在显式转换(您是否缺少强制转换?)

Visual Studio tells me: Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

为什么?

推荐答案

int 是一种值类型,只能装箱至 object -它不会继承来自对象。由于无论如何,您都在使用 IEnumerable< object> ,所以应该可以:

int is a value type and can only be boxed to object - it doesn't inherit from object. Since you're using an IEnumerable<object> anyway, this should work:

IEnumerable intIds = new List<int>() { 1, 2, 3 };

这篇关于为什么我不能分配List&lt; int&gt;到IEnumerable&lt; object&gt;在.NET 4.0中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆