当我尝试从数组对象调用它时,从ILIST接口中删除方法

发布于 2025-01-28 07:20:57 字数 892 浏览 2 评论 0原文

根据官方

  • iList
  • ienumerable

docs 对于iList,我看到其中列出的一种方法是做出以下操作的方法:

从iList中删除特定对象的第一次出现。

我想使用此方法,因此我编写了以下最小程序:

class RemoveAllOccurences {

    static void Main() 
    {
        int[] a = {1, 0, 0, 3};
        
        a.Remove(0);

    }
}

然后,我对以下内容进行了编译:

csc test.cs -out:test.exe

运行可执行文件丢弃以下错误:

remove_issue.cs(7,11):错误cs1061:'int []'不包含“删除”的定义,而无访问的扩展方法'删除'接受类型'int []'的第一个参数可以是找到(您是否缺少使用指令或装配给参考?)

我不确定为什么删除未被识别,因为正如我之前提到的,它是iList接口的一部分文档。

我在这里做错了什么?

According to the official docs, arrays in C# implement the following interfaces:

  • IList
  • IEnumerable

In the docs for IList, I see that one of the listed methods is a Remove method which does the following:

Removes the first occurrence of a specific object from the IList.

I wanted to use this method, so I wrote the following minimal program:

class RemoveAllOccurences {

    static void Main() 
    {
        int[] a = {1, 0, 0, 3};
        
        a.Remove(0);

    }
}

I then compiled with the following:

csc test.cs -out:test.exe

Running the executable threw the following error:

remove_issue.cs(7,11): error CS1061: 'int[]' does not contain a definition for 'Remove' and no accessible extension method 'Remove' accepting a first argument of type 'int[]' could be found (are you missing a using directive or an assembly reference?)

I'm not sure why Remove is not recognized, since as I mentioned before it is part of the IList interface shown in the docs.

What am I doing wrong here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱人如己 2025-02-04 07:20:57

数组实施iList.remove通过 显式接口实现 ,这意味着您只能通过带有compile-time类型的接口类型的引用访问它。因此,例如:

int[] a = {1, 0, 0, 3};
IList list = a;
list.Remove(0);

编译没有任何问题。但是,由于数组为固定尺寸 - remove and add 操作没有使操作没有使得无法制作对他们的感觉。这就是为什么通过显式接口实现实现这些方法的原因,以避免您不适当地使用它们...

Arrays implement IList.Remove via explicit interface implementation, which means you can only access it via a reference with a compile-time type of the interface type. So for example:

int[] a = {1, 0, 0, 3};
IList list = a;
list.Remove(0);

That compiles with no problem. However, it will then throw an exception (NotSupportedException) at execution time because arrays are of fixed size - Remove and Add operations don't make sense on them. That's why those methods are implemented with explicit interface implementation, to avoid you using them inappropriately...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文