现在,我知道在 C# 中,数组是一个固定大小的集合。您不能对它们使用 RemoveAt
方法是有道理的,except that the System.Array
class, which all array types extend from, implements the System.Collections.IList
interface ,这需要一个 RemoveAt
方法。
如果you upcast an array to an IList
, or pass it to a method taking an IList
as an argument ,您可以对其调用 .RemoveAt
,这将在运行时抛出 NotSupportedException
。但是,如果我不向上转换它,and call it directly ,它将导致编译器错误,“int[]”不包含“RemoveAt”的定义
,尽管该方法显然存在。
什么允许编译器在编译时捕获此 NotSupportedException
?它是数组的特殊情况,还是我可以定义自己的类来实现这种行为?
最佳答案
Array 确实不应该实现 IList,因为它没有完全实现该接口(interface),因此会出现 NotSupportedException,但它可能是为了方便而添加的。
调用 Array.RemoveAt 时无法编译的原因是 Array 实现了 IList 的方法 explicitly这意味着该方法不可用,除非它被转换为该接口(interface)。
这看起来像:
class OnlySortOfAList : IList
{
void IList.RemoveAt(int Index) // note the lack of access modifier
{
throw new NotSupportedException();
}
}
关于c# - 为什么我不能在数组上调用 RemoveAt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52520920/