c# - 转换 List<ClassA> 时出现问题,其中 ClassA :Generic<Int32> to List<Generic<Int32>>

标签 c# generics covariance

我还有下一个类:

public class EntityBase<T>
{
    public T Id { get; set; }

}

它的实现者:

public class ClassA : EntityBase<Int32>
{
     ...
}

public class ClassB : EntityBase<Int64>
{
     ...
}

在代码中,它不知道类 - ClassAClassB 它只知道 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> 很容易允许它因为您无法为此类集合添加新值。

这就是为什么他们有 inout在泛型声明中。

关于c# - 转换 List<ClassA> 时出现问题,其中 ClassA :Generic<Int32> to List<Generic<Int32>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15808285/

相关文章:

c# - C# 中的 List<T<U>> 其中 T 和 U 是接口(interface)

generics - 我对同一个类有两个 Kotlin 扩展方法,但是具有不同的通用签名并且编译器会提示

java - 在继承层次结构中声明具有两个类型参数的方法的正确方法

c++ - 绕过 C++/STL 中的容器协变

java - 为什么 A->B 不构成 List<A>->List<B>?这不会消除对通配符的需要吗?

c# - 无法使用 asp.net 中的 twilio 短信服务发送回复短信

c# - c# foreach for linq 的性能差异

c# - 在运行时创建 WCF 服务时出现 ActionNotSupported 错误

返回值为void时的C#out参数

具有泛型的Scala类型类