c# - 为什么我不能在数组上调用 RemoveAt?

标签 c# arrays compiler-errors

现在,我知道在 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/

相关文章:

c# - Visual C# 窗体右键单击按钮

C - strcmp() 数组中的两个字符串

c - 传递给 pgplot 时,是否有一种 O(1) 方法来分离复数数组的实部和虚部?

java - 捕获 Java 中的转换问题、JLS 的 WRT 协调和实际的 JDK 行为

macos - 如何在 OSX Mavericks 上构建 OpenBLAS

c# - INotifyPropertyChanged.PropertyChanged 已触发,但 UI 在表单加载后未更新

c# - 如何将用户输入的字符串与任何表示本地主机的内容匹配?

ios - NSUserDefaults 只保存数组中的一个元素

ios - 类型 '(Class) -> () -> (Class)' 的值没有成员 'variable'

c# - 返回选定的指定列