问题描述
我正在查看IOrderedEnumerable的声明,我很惊讶它的TElement类型参数不是协变的。
I was Looking at the declaration of IOrderedEnumerable an I was suprised that it isn't covariant in it's TElement type parameter .
public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>, IEnumerable
{
IOrderedEnumerable<TElement> CreateOrderedEnumerable<TKey>(Func<TElement, TKey> keySelector, IComparer<TKey> comparer, bool descending);
}
不进行协变的原因是什么?
What's the reason for which it was not made covariant ?
推荐答案
这是一个疏忽,并且已在.NET Core中修复。这是关于此的(已关闭),这里是对其进行了修复。
It's an oversight and that was fixed in .NET Core. Here is (closed) issue about that and here is pull request which fixes it.
它没有完全固定我认为.NET版本是一个重大变化。例如(想法取自此,它涉及另一个重大更改,但也适用于此):
It's not getting fixed in full .NET version I think because that's a breaking change. For example (idea is taken from this answer which is about another breaking change, but applies here too):
public class Base
{
public void DoSomething(IOrderedEnumerable<string> strings)
{
Console.WriteLine("Base");
}
}
public class Derived : Base
{
public void DoSomething(IOrderedEnumerable<object> objects)
{
Console.WriteLine("Derived");
}
}
然后致电
Derived d = new Derived();
d.DoSomething(new List<string>().OrderBy(c => c));
如果 IOrderedEnumerable
不是协变的- Base
方法将被调用。现在假设我们将其更改为协变。下次编译此代码时,突然调用 Derived
方法。
If IOrderedEnumerable
is not covariant - Base
method would be called. Now suppose we change that to covariant. When we next time compile this code, suddenly Derived
method is called.
这篇关于为什么接口IOrderedEnumerable< T> T不是协变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!