我有下课:public class EntityBase<T>{ public T Id { get; set; }}它的实现者:public class ClassA : EntityBase<Int32>{ ...}public class ClassB : EntityBase<Int64>{ ...}在不知道类-ClassA和ClassB的代码中,它仅知道EntityBase 的存在,我这样做是这样的: // Here for sure I get the list of `ClassA` object obj = GetSomeHowListOfClassA(); List<EntityBase<Int32>> listOfEntityBases = (List<EntityBase<Int32>>)obj;我得到错误:Unable to cast object of type 'System.Collections.Generic.List`1[...ClassA]' to type 'System.Collections.Generic.List`1[...EntityBase`1[System.Int32]]'.我这样修复:var listOfEntityBases = new List<EntityBase<Int32>>(obj);但是我不喜欢这种方式,因为我正在创建新的List 。有没有办法铸造它?谢谢。 最佳答案 您不能以这种方式进行投射,因为:C#中的协方差不适用于类;接口IList<T>和ICollection<T>不是协变的。您唯一可以做的选择(复制列表除外)是对IEnumerabe<T>的强制转换:var listOfEntityBases = (IEnumerable<EntityBase<Int32>>)obj;关于c# - 在将List <Class>转换为List <Generic <Int32 >>的情况下出现问题,方法是将A:Generic <Int32>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15808285/
10-13 07:03