我问是因为我认为 C# 要求在类中实现所有接口(interface)。使用 ILSpy,我发现 IReadOnlyList.this[int index] 索引器实现不在类列表中。
这是经过编辑的类声明片段(未列出所有内容)
public class List < T > : IList <T >, IReadOnlyList < T >
IList<T>.this[int index]
在那里,但不IReadOnlyList<T>.this[int index]
.
看起来很奇怪,这首先是如何编译的? .NET Framework 中是否有一些特殊的调味料可以实现这一点?
最佳答案
我认为您使用的工具造成了困惑。列表中的索引器未明确实现为 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; }
这是一个简单的片段,其中包含一个实现两个接口(interface)的类,以证明可以为两个接口(interface)提供一个实现。
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();
}
关于c# - 为什么 List<T> 不显式实现 IReadOnlyList<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52141958/