本来想用如下这种方法进行强制转换: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]"
List<int> obj2 = (List<int>)obj1;但是,报错,说是无法将类型"System.Collections.Generic.List'l[System.Object]"的对象强制转换为类型"System.Collections.Generic.List'l[System.Int32]"
al.Add(33);这样会少约束,有了泛型就可以很大程度上避免这样的不良状态况发生了,也避免了
box unbox 保证集合是强类型 而大大提高了运行效率;对类而言只是继承关系的才可以这第转换吧 ;object o=obj1;
List<int> lints=o as List<int>; 估计lints也会是null 吧
{
转换;
}
//--我给你剪一段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的转换是装箱转换,而不是引用转换。