请看以下示例(部分取自MSDN博客):
class Animal { }
class Giraffe : Animal { }
static void Main(string[] args)
{
// Array assignment works, but...
Animal[] animals = new Giraffe[10];
// implicit...
List<Animal> animalsList = new List<Giraffe>();
// ...and explicit casting fails
List<Animal> animalsList2 = (List<Animal>) new List<Giraffe>();
}
Run Code Online (Sandbox Code Playgroud)
这是一个协方差问题吗?这将在未来的C#版本中得到支持吗?是否有任何聪明的解决方法(仅使用.NET 2.0)?
为什么C#编译器不允许泛型集合中的多态类型(T)参数(即List [T])?
以"A"和"B"为例,其中"B"是"A"的子类
class A { }
class B : A { }
Run Code Online (Sandbox Code Playgroud)
并考虑一个带有'A'类型列表的函数
void f(List<A> aL) { }
Run Code Online (Sandbox Code Playgroud)
用"B"类型的列表调用
List<B> bL = new List<B>();
f(bL);
Run Code Online (Sandbox Code Playgroud)
给出以下错误
ERROR: cannot convert from List<B> to List<A>
Run Code Online (Sandbox Code Playgroud)
违反了什么语义规则?
除此之外,还有一个"优雅"的意思,除了循环和铸造每个元素(我想要一些糖)?谢谢.
请考虑以下情形.
文档 - >部分 - >正文 - >项目
文档有部分,一个部分包含一个正文.正文包含一些文本和项目列表.这些项目就是问题所在.有时这些项是字符串的基本列表,但有时这些项包含自定义数据类型的列表.
所以:
public class Document
{
public Section[] Sections{get;set;}
}
public class Section
{
public SectionType Type{get;set;}
public Body {get;set;}
}
public class Body
{
//I want the items to be depending on the section type.
//If e.g. the sectiontype is experience, I want the Items to be created with type //Experience. If sectiontype is default I want the Items to be created with type string
public Items<T> Items {get;set;}
}
public …Run Code Online (Sandbox Code Playgroud) public class A {}
public class B : A {}
Run Code Online (Sandbox Code Playgroud)
现在有什么最好的方法让这个工作
List<A> a;
List<B> b = new List<B>();
a = b; // throw Cannot convert List<B> to List<A>
Run Code Online (Sandbox Code Playgroud)
谢谢
private Dictionary<Type, List<IDataTransferObject>> dataStore = new Dictionary<Type, List<IDataTransferObject>>();
public void Insert<T>(T dto) where T : IDataTransferObject
{
if (!dataStore.ContainsKey(typeof(T)))
{
dataStore.Add(typeof(T), new List<T>());
}
dataStore[typeof(T)].Add(dto);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给出了dataStore.Add行的编译错误,因为它不喜欢我尝试将a分配List<T>给a List<IDataTransferObject>.由于我的方法将T限制为只有IDataTransferObject,因此.Net 4中的协方差/逆变量不应该允许这个代码吗?
我知道我可以改变它来做新的List<IDataTransferObject>它会起作用,但我很好奇为什么原始代码不起作用.