为什么List<T>没有明确实现IReadOnlyList<T>?

3
我想知道这个问题是因为我认为C#需要在类中实现所有接口。使用ILSpy,我发现IReadOnlyList.this[int index]索引器的实现不在List类中。
这是类声明的编辑片段(未列出所有内容)。
public class List < T > : IList <T >, IReadOnlyList < T >

List类声明

IList<T>.this[int index]是存在的,但IReadOnlyList<T>.this[int index]却不存在。

ILSpy搜索

这似乎很奇怪,这首先如何编译?.NET Framework中是否有一些特殊的技巧可以实现这一点?


1
为什么要使用ILSpy,当你可以查看源代码呢?https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646 - undefined
3
@Alex.A - 这是源代码中的内容。第174行是 public T this[int index],它实现了 IReadOnlyList<T> - undefined
2
@Alex 编译完全正常。不确定你为什么认为它不能编译 - 你必须实现接口所需的内容。这并不意味着你不能实现更多的内容。 - undefined
2
@Alex.A 不,你需要将属性和索引器视为调用 Foo GetFoo()void SetFoo(Foo value) 的便利方式。接口只要求存在 get 方法,不关心是否存在 set 方法。 - undefined
1
谢谢。我忘了接口只指定了类必须实现的最小要求,而不是最大要求。 - undefined
显示剩余2条评论
2个回答

3
我认为你正在使用的工具导致了混淆。列表中的索引器没有明确实现为 IList 接口。
public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList
{
    (...)
    public T this[int index] { get; set; }

这是一个简单的代码片段,其中包含一个类,实现了两个接口,以证明为两个接口提供单一实现是可行的。

    public interface IOne{void MyMethod();}

    public interface ITwo{void MyMethod();}

    public class MyClass: IOne, ITwo
    {
        public void MyMethod()
        {
            Console.WriteLine("Hello!");
        }
    }

    public static void Main()
    {
        new MyClass().MyMethod();
    }

0

要拥有预先实现的 IReadOnlyCollectionIReadOnlyList 类型,可以使用 ReadOnlyCollection。请查看以下示例代码:

 public void Test()
    {
        IList<int> myList = new List<int>() { 1, 10, 20 };
        IReadOnlyList<int> myReadOnlyCollection = new ReadOnlyCollection<int>(myList);
        GetElement(myReadOnlyCollection,1);
    }


 private int GetElement(IReadOnlyList<int> list,int index)
    {
        return list[index];
    }

//Output: 10

1
你的回答似乎暗示List没有实现IReadOnlyList,这是不正确的。它确实实现了它。"为什么你期望在List中找到IReadOnlyList的实现呢?" - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接