简体   繁体   English

为什么协方差不能在没有参数的情况下工作?

[英]Why doesn't covariance work with out parameters?

The following code doesn't compile: 以下代码无法编译:

public void CreateStringList(out List<string> newList)
{
    newList = new List<string>();
}

...

IEnumerable<string> myList;
CreateStringList(out myList);

The error given is: 给出的错误是:

The out parameter type doesn't match the parameter type out参数类型与参数类型不匹配

My question is... why doesn't this work? 我的问题是... 为什么不起作用? IEnumerable<string> is covariant with List<string> , so the assignment will never violate type-safety. IEnumerable<string>List<string> IEnumerable<string>是协变的,因此赋值永远不会违反类型安全性。 And you're not allowed to use an out parameter before assigning it, so the fact that the previous value of newList might not have been a List<string> is irrelevant. 并且在分配它之前不允许使用out参数,因此newList的先前值可能不是List<string>的事实是无关紧要的。

Am I missing something? 我想念什么吗?

Quoting Eric Lippert's answer to a very similar question ( Why can't ref and out parameters be variant? ): 引用埃里克·利珀特(Eric Lippert)对一个非常相似的问题的答案为什么不能将ref和out参数作为变量? ):

The only difference between "out" and "ref" is that the compiler forbids reading from an out parameter before it is assigned by the callee, and that the compiler requires assignment before the callee returns normally. “ out”和“ ref”之间的唯一区别是, 编译器在被调用方分配之前禁止读取out参数,并且编译器需要在被调用方正常返回之前进行分配。

This implies that languages other than C# don't have this restriction, and could use the parameter as an input. 这意味着除C#之外的其他语言没有此限制,可以使用参数作为输入。 Since an IEnumerable<string> cannot be a List<string> , this is not allowed. 由于IEnumerable<string>不能为List<string> ,所以不允许这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM