gpt4 book ai didi

c# - 为什么 `IList` 不继承自 `IReadOnlyList` ?

转载 作者:IT王子 更新时间:2023-10-29 04:21:52 24 4
gpt4 key购买 nike

IReadOnlyList<T>是在 .NET 4.5 中引入的,有那么一刻我认为拼图的缺失部分终于被插入到位:一种传递真正的只读可索引接口(interface)的方法,以前我必须使用我自己的只读接口(interface)并创建包装类围绕一切。

我期望界面被放置在“自然”层次结构中,理想情况下是:

IEnumerable<T> 
.GetEnumerator()
-> IReadOnlyCollection<T> : IEnumerable<T>
.Count
-> IReadOnlyList<T> : IReadOnlyCollection<T>
.Item[...]
-> IList<T> : IReadOnlyList<T>
.Add(...)
.Clear()
.Contains(...)
(etc)

但是,事实证明, IList<T>不继承自 IReadOnlyList<T> .

这有什么原因吗?

一些说明:

请注意 IReadOnlyList<T>只是一个契约,它声明列表提供了一种获取列表计数并读取特定索引处的值的方法。它的命名很糟糕,因为它没有强制执行只读的实际实现。

A List<T>工具 IEnumerable<T> , 一个 IList<T>继承自 IEnumerable<T> ,但这并不意味着这些类只能被枚举。

所以,如果你想将一个列表传递给一个方法,并且只允许它被索引(读取),而不是被修改,你需要将它包装在一个新的实例中。同时,您可以将其传递给接受 IEnumerable<T> 的方法。或 IList<T> 无需 包装它。这就是我发现的问题。

我也相信专有名称应该是 ICountable对于 IReadOnlyCollectionIIndexable对于 IReadOnlyList :

IEnumerable<T> 
.GetEnumerator()
-> ICountable<T> : IEnumerable<T>
.Count
-> IIndexable<T> : ICountable<T>
.Item[...]
-> IList<T> : IIndexable<T>
.Add(...)
.Clear()
.Contains(...)
(etc)

最佳答案

@w.b 放一个链接到New interfaces IReadOnlyList and IReadOnlyDictionary在包含答案的评论中:

Why did we not change the existing interfaces to extend the read-only interfaces?

It looks like a reasonable assumption that it works because the read-only interfaces are purely a subset of the read-write interfaces. Unfortunately, it is incompatible because at the metadata level every method on every interface has its own slot (which makes explicit interface implementations work).


Immo Landwerth | .NET Framework Team (BCL) | http://blogs.msdn.com/b/bclteam/

为了更清楚地解释这一点:

假设为 .NET 4.0 编写的程序包含类 MyList<T>实现 IList<T> .它显然无法实现 IReadOnlyList<T>因为该接口(interface)不存在。

现在假设系统管理员安装了 .NET 4.5 并假设 .NET 4.5 生成了 IList<T>实现 IReadOnlyList<T> .

如果程序随后被加载,运行时将检测到 MyList<T>声称要执行IList<T> , 但实际上并没有实现所有的方法:它没有实现 IReadOnlyList<T>的方法。该程序将不再有效。

C# 编译器可能能够按名称匹配方法,但运行时不会这样做。由于 .NET 4.5 应该具有向后二进制兼容性,因此无法扩展接口(interface)以实现其他接口(interface),即使这些其他接口(interface)包含所需方法的严格子集也是如此。

关于c# - 为什么 `IList<T>` 不继承自 `IReadOnlyList<T>` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938995/

24 4 0