我还有下一个类:
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<EntityBase<Int32>> listOfEntityBases = (List<EntityBase<Int32>>)obj;
这意味着在该行之后您可以说以下内容
listOfEntityBases.Add(new EntityBase<Int32>());
但实际上这一行同时会添加EntityBase<Int32>
反对你的obj
类型 List<ClassA>
- 这绝对是InvalidCast。
因此,您不能声明与 List<ClassA>
相同 变量和List<EntityBase<Int32>>
在同一时间。
尽管如此,IEnumerable<T>
很容易允许它因为您无法为此类集合添加新值。
这就是为什么他们有 in
和out
在泛型声明中。
关于c# - 转换 List<ClassA> 时出现问题,其中 ClassA :Generic<Int32> to List<Generic<Int32>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15808285/