C# 为什么';t列表<;T>;显式实现IReadOnlyList<;T>;?

C# 为什么';t列表<;T>;显式实现IReadOnlyList<;T>;?,c#,list,generics,C#,List,Generics,我这样问是因为我认为C#要求在类中实现所有接口。使用ILSpy,我发现IReadOnlyList。这个[int index]索引器实现不在类列表中 这是经过编辑的类声明片段(并非列出的所有内容) 公共类列表:IList、IReadOnlyList IList.this[int index]在那里,但不是IReadOnlyList.this[int index] 看起来很奇怪,这是怎么编译的?在.NET Framework中是否有一些特殊的工具支持此功能?我认为您使用的工具造成了混乱。列表中

我这样问是因为我认为C#要求在类中实现所有接口。使用ILSpy,我发现IReadOnlyList。这个[int index]索引器实现不在类列表中

这是经过编辑的类声明片段(并非列出的所有内容)

公共类列表:IList、IReadOnlyList

IList.this[int index]
在那里,但不是
IReadOnlyList.this[int index]


看起来很奇怪,这是怎么编译的?在.NET Framework中是否有一些特殊的工具支持此功能?

我认为您使用的工具造成了混乱。列表中的索引器没有显式实现为
IList
implementation

public class List<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IList<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection, IList
{
    (...)
    public T this[int index] { get; set; }

要获得预先实现的
IReadOnlyCollection
IReadOnlyList
类型,可以使用
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
公共无效测试()
{
IList myList=new List(){1,10,20};
IReadOnlyList myReadOnlyCollection=新的ReadOnlyCollection(myList);
GetElement(myReadOnlyCollection,1);
}
私有int GetElement(IReadOnlyList,int索引)
{
返回列表[索引];
}
//产出:10

如果可以看到源代码,为什么要使用ILSpy@Alex.A-在来源里。第174行是这个[int index]的
public行,它实现了
IReadOnlyList
@Alex。不确定为什么您认为它不会-您必须实现接口所需的功能。这并不意味着限制您实现更多功能。@Alex.A不,您需要将属性和索引器看作是调用
Foo GetFoo()
void SetFoo(Foo value)
的一种方便。接口只要求get方法存在,它不关心set方法是否存在。谢谢。我忘记了接口只指定类必须实现的最小值,而不是最大值。您的回答似乎暗示
List
没有实现
IReadOnlyList
。这是不正确的。它确实实现了它<代码>为什么您希望在列表中找到IReadOnlyList的实现
    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();
    }
 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