【发布时间】:2014-12-14 01:07:41
【问题描述】:
以下代码无法编译:
public void CreateStringList(out List<string> newList)
{
newList = new List<string>();
}
...
IEnumerable<string> myList;
CreateStringList(out myList);
给出的错误是:
out参数类型与参数类型不匹配
我的问题是... 为什么这不起作用? IEnumerable<string> 与 List<string> 是协变的,因此分配永远不会违反类型安全。并且在分配之前不允许使用out 参数,因此newList 的先前值可能不是List<string> 的事实无关紧要。
我错过了什么吗?
【问题讨论】:
-
这不起作用与
out无关 -
在 Eric 对链接问题的回答中特别参见“结论 4”。
标签: c# .net covariance contravariance