Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c# - Why does List<T> implement IList<T>, ICollection<T> and IEnumerable<T>?

If you go to definition of List<T> you would see the following:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>

IList<T> already inherits from both ICollection<T> and IEnumerable<T>.

Wouldn't it have been sufficient if List<T> only implemented IList<T>?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it makes no difference in this case. In some cases it can make a difference, if you're using a base class which already implements an interface but you wish to reimplement it yourself explicitly - but in this case there's no base class (other than the implicit object) and it would have behaved exactly the same way.

Contrary to my recollections, I don't believe there's a difference in the way the class is represented in metadata whether the code explicitly declares all the interfaces or not. Here's an example:

interface IFoo {}
interface IBar : IFoo {}

class FooBar1 : IBar {}
class FooBar2 : IBar, IFoo {}

Both ildasm and Reflector show the same information for FooBar1 and FooBar2... it shows both of them implementing IBar and IFoo.

In other words, we can't tell whether the original source code for List<T> actually specifies all the interfaces or not. Maybe it does, maybe it doesn't - but it doesn't matter either way.

EDIT: For completeness, I also checked the cases where you're extending two interfaces with another interface. I can't find a difference in the metadata in that case, either. I'm sure I remember some situation in which it was evident, but I can't find it now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...