协方差和IList

协方差和IList,第1张

协方差和IList

更新:从.NET 4.5开始

IReadOnlyList<out T>
IReadOnlyCollection<outT>
这两者都是协变的;后者基本上是
IEnumerable<outT>
加号
Count
; 前者补充说
T this[int index] {get;}
。还应注意,
IEnumerable<out T>
从.NET
4.0开始是协变的。

双方

List<T>
ReadOnlyCollection<T>
(通过
List<T>.AsReadonly()
)实现这两个。


如果只有

get
索引器,则只能是协变的,即

public T this[int index] { get; }

但是所有主要收藏都有

{get;set;}
,这很尴尬。我不知道有什么可以满足要求的,但是您可以 包装 起来,即编写一个扩展方法:

var covariant = list.AsCovariant();

这是一个包装器

IList<T>
,仅暴露
IEnumerable<T>
和和
get
索引器…?应该只有几分钟的工作…

public static class Covariance{    public static IIndexedEnumerable<T> AsCovariant<T>(this IList<T> tail)    {        return new CovariantList<T>(tail);    }    private class CovariantList<T> : IIndexedEnumerable<T>    {        private readonly IList<T> tail;        public CovariantList(IList<T> tail)        { this.tail = tail;        }        public T this[int index] { get { return tail[index]; } }        public IEnumerator<T> GetEnumerator() { return tail.GetEnumerator();}        IEnumerator IEnumerable.GetEnumerator() { return tail.GetEnumerator(); }        public int Count { get { return tail.Count; } }    }}public interface IIndexedEnumerable<out T> : IEnumerable<T>{    T this[int index] { get; }    int Count { get; }}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5505798.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存