为什么System.Array类实现IList但不提供Add() [英] Why System.Array class implements IList but does not provide Add()

查看:129
本文介绍了为什么System.Array类实现IList但不提供Add()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

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

投入构建:

错误CS1061:"System.Array"不包含"Add"的定义,并且找不到扩展方法"Add",该扩展方法接受类型为"System.Array"的第一个参数(您是否缺少using指令或程序集参考?)

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接口具有Add()方法,但是为什么数组不实现它?

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:

为什么Array实际上不提供 Add(),或者更好,为什么首先必须实现IList?除了实现IList之外,它可能是另一个接口(例如IArray),该接口仅对IList -e.g的Array成员有用. IsFixedSizeIsReadOnlyIndexOf() ...只是一个想法.

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.

推荐答案

是的,如果System.Array实现了IReadOnlyList或类似的接口,似乎应该是一个更好的设计.但是,IReadOnlyList<T>出现在 .Net 4.5 中,而System.Array保留在最初的 .Net 1.0 中.微软恕我直言,通过显式接口实现

Yes, it seems that it should have been a better design if System.Array had implemented IReadOnlyList or alike interface. However, IReadOnlyList<T> appeared in .Net 4.5 while System.Array stays from the initial .Net 1.0. Microsoft, IMHO, did their best and hid Add via explicit interface implementation

http://referencesource.microsoft.com/#mscorlib/system/array.cs,156e066ecc4ccedf

  ...
int IList.Add(Object value)
{
    throw new NotSupportedException(Environment.GetResourceString("NotSupported_FixedSizeCollection"));
} 
  ...

所以你做不到

int[] myArr = { 1, 2 };

myArr.Add(3);

,但是您可以坚持使用Add(并抛出NotSupportedException)通过

but you can insist on using Add (and get NotSupportedException thrown) via

((IList) myArr).Add(3);

甚至

if (!myArr.IsFixedSize) {
  // we have very strange array, let's try adding a value to it
  ((IList) myArr).Add(3);
}

这篇关于为什么System.Array类实现IList但不提供Add()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆