问题描述
定义System.Linq.ILookUp读取
The definition System.Linq.ILookUp reads
interface ILookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>, IEnumerable {
int Count {
get;
}
IEnumerable<TElement> this[TKey key] {
get;
}
bool Contains(TKey key);
}
由于IEnumerable在IGrouping< TKey,TElement> ;、 IGrouping< TKey,TElement>中是协变的.在TElement中是协变的,并且接口仅将TElement作为返回类型公开,我假设ILookup在TElement中也是协变的.确实,定义
Since IEnumerable is covariant in IGrouping<TKey, TElement>, IGrouping<TKey, TElement> is covariant in TElement and the interface only exposes TElement as a return type, I would assume that ILookup is also covariant in TElement. Indeed, the definition
interface IMyLookup<TKey, out TElement> : IEnumerable<IGrouping<TKey, TElement>>, IEnumerable {
int Count {
get;
}
IEnumerable<TElement> this[TKey key] {
get;
}
bool Contains(TKey key);
}
编译没有问题.
那么,原始定义中缺少 out 关键字的原因可能是什么?可以添加Linq的将来版本吗?
So, what might be the reason why the out keyword is missing in the original definition? Might it be added future versions of Linq?
推荐答案
跟踪MSDN文档,泛型中的协方差和相反方.在此之前,从.NET Framework 2.0到.NET Framework 3.5一直存在IEnumerable<T>
.然后在.NET Framework 4.0中,我们可以看到类型参数为T
作为协方差的IEnumerable<out T>
.
Tracking the MSDN documentation, Covariance and Contravariance in Generics have been introduced in .NET Framework 4 Prior to that, there was IEnumerable<T>
since the .NET Framework 2.0 up to .NET Framework 3.5. Then in .NET Framework 4.0 we can see IEnumerable<out T>
with type parameter T
as covariance.
IGrouping<TKey, TElement>
和ILookup<TKey, TElement>
已经存在.在.NET Framework 4.0中,前者已更新为IGrouping<out TKey, out TElement>
,但省略了后者,但未指定原因.
IGrouping<TKey, TElement>
and ILookup<TKey, TElement>
have existed since .NET Framework 3.5. In .NET Framework 4.0 the former has been updated to IGrouping<out TKey, out TElement>
but the latter has been omitted without specifying the reason.
TKey
不能是协变的,因为Contains(TKey)
和this[TKey]
的实现可以防止这种情况.
TKey
can't be covariant since implementations of Contains(TKey)
and this[TKey]
prevent that.
关于TElement
的问题尚不清楚.我不相信设计师会错过它.也许原因在于未来的计划.或者他们想防止出现以下情况,但我不知道为什么:
With regard to TElement
the issue is not clear. I don't believe that designers just missed it. Perhaps cause lies in the plans for the future. Or they wanted to prevent something like the below, but I don't know why:
string[] strings = new[] {"a", "a", "b", "b", "b", "c"};
ILookup<string, string> lookup = strings.ToLookup(s => s); // Valid.
ILookup<string, object> lookup = strings.ToLookup(s => s); // Now invalid, but would correct if TElement was covariant (out TElement).
也有其他作者关注该问题:
There are also other authors, that pay attention to that issue:
ToLookup :
这篇关于ILookup< TKey,TElement>在TElement中(被声明)是协变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!