Why System.Array class implements IList but does n

2019-02-12 23:42发布

This code:

int[] myArr = { 1, 2 };
myArr.Add(3);

throws on Build:

error CS1061: 'System.Array' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

IList interface has the Add() method, but why the Array does not implement it?

UPDATE: I see from the answers that it DOES implement it explicitly, OK, I get it, thank you, I should better stick to the question:

Why Array does not actually provide Add(), OR, better, why did it have to implement IList in the first place? Instead of implementing IList, it could be another interface (e.g. IArray) which could have ONLY the useful for Array members of IList -e.g. IsFixedSize, IsReadOnly, IndexOf()... just a thought.

7条回答
虎瘦雄心在
2楼-- · 2019-02-13 00:22

System.Array class implements IList but does not provide Add()

Of course it does via explicit implementation (there is no way to implement interface and not implement some members).

Why the array implements IList?

Well, mainly to indicate that it supports indexer.

But in fact array implements one of the valid IList usages. The IList interface has a property called IsFixedSize, which according to the documentation

Gets a value indicating whether the IList has a fixed size.

and then

A collection with a fixed size does not allow the addition or removal of elements after the collection is created, but it allows the modification of existing elements.

So array implementation returns IsFixedSize = true and throws NotSupportedException inside Add, Insert, Remove and RemoveAt methods.

查看更多
登录 后发表回答