List 类型的数据如何转换为List类型的数据

stg609 2009-03-06 07:07:54
本来想用如下这种方法进行强制转换:

List<object> obj1 = new List<object>{1,2,3};
List<int> obj2 = (List<int>)obj1;

但是,报错,说是无法将类型"System.Collections.Generic.List'l[System.Object]"的对象强制转换为类型"System.Collections.Generic.List'l[System.Int32]"
...全文
230 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
stg609 2009-03-10
  • 打赏
  • 举报
回复
在MSDN上找到一个方法是ConvertTo<>()
ProjectDD 2009-03-07
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 guoyichao 的回复:]
4.0才支持协变和逆变,允许这样转换。
[/Quote]

//--我给你剪一段C#4.0白皮书上的内容参考一下,以做补充--

Limitations
限制
Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion.

变性类型参数只能在接口和委托类型中声明,这是CLR的限制。变性只能应用在类型参数的按引用转换之间。例如,IEnumerable<int>不能作为IEnumerable<object>使用,因为从int到object的转换是装箱转换,而不是引用转换。

cppfaq 2009-03-06
  • 打赏
  • 举报
回复
目前只能遍历/unbox,然后加进去
云想慕尘 2009-03-06
  • 打赏
  • 举报
回复
if(obj1 is obj2)
{
转换;
}
fskjb01 2009-03-06
  • 打赏
  • 举报
回复
如果有继承关系的话,通过多态就可以,否则不行的!!
guoyichao 2009-03-06
  • 打赏
  • 举报
回复
4.0才支持协变和逆变,允许这样转换。
ProjectDD 2009-03-06
  • 打赏
  • 举报
回复
这样转换,又没有直接继承关系什么的;

泛型推出就是强调类型的单一不要象原来ArrayList al; 那样,可能

al.Add("aaa");
al.Add(33);

这样会少约束,有了泛型就可以很大程度上避免这样的不良状态况发生了,也避免了
box unbox 保证集合是强类型 而大大提高了运行效率;

对类而言只是继承关系的才可以这第转换吧 ;

object o=obj1;
List<int> lints=o as List<int>; 估计lints也会是null 吧
List 转为 ListClass> List<Object> 转为 List<MyClass> 第一种:objlist.ConvertAll(o => (MyClass)o) 第二种: List<MyClass>mylist=newList<MyClass>(); ...

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧