简体   繁体   English

尝试添加索引器时如何解决C#编译器错误CS0102?

[英]How do I resolve C# compiler error CS0102 when trying to add an indexer?

So I'm trying to port a java Bag class over to C#. 因此,我试图将java Bag类移植到C#。 I know I've done it wrong here, because a test of this code in a foreach statement produces only the first two added items, but this is not my primary question. 我知道我在这里做错了,因为在foreach语句中对该代码进行测试只会产生添加的前两个项目,但这不是我的主要问题。

The compiler throws a CS0102 when I try to add an indexer to the Bag class, complaining that Bag<Item> already contains a definition for Item . 当我尝试将索引器添加到Bag类时,编译器抛出CS0102,抱怨Bag<Item>已经包含Item的定义。 But I can create a method public Item Get(int i) , which does the very same thing just fine. 但是我可以创建一个方法public Item Get(int i) ,它做同样的事情就好了。 Why is this happening and how can I create an indexer for this class? 为什么会发生这种情况,如何为此类创建索引器?

Edit The exact error is: Bag.cs(15,15): Error CS0102: The type Algorithms4e.ch1.Bag<Item>' already contains a definition for Item' (CS0102) 编辑确切的错误是:Bag.cs​​(15,15):错误CS0102:类型Algorithms4e.ch1.Bag<Item>' already contains a definition for Item' Algorithms4e.ch1.Bag<Item>' already contains a definition for (CS0102)

Just as a side note, I know the Bag class is not supposed to use an indexer, but it's the principle of the thing; 顺便提一句,我知道Bag类不应该使用索引器,但这是事情的原理。 I should be able to add an indexer to any class right? 我应该能够向任何类添加索引器吗?

I'm running Mono C# compiler version 3.2.8.0 under Ubuntu 14.04.2 LTS, if that helps at all. 我在Ubuntu 14.04.2 LTS下运行Mono C#编译器版本3.2.8.0,如果有帮助的话。

Please let me know if y'all need any more information, or if I'm posting this is the right place to begin with. 如果所有人都需要更多信息,或者如果我要发布此信息,那么请告诉我。 I'd be happy to update the question. 我很乐意更新这个问题。

public class Bag<Item> : IEnumerable<Item> {
    private int N;               // number of elements in bag
    private Node<Item> first;    // beginning of bag

    // helper linked list class
    private class Node<T> {
        public T item;
        public Node<T> next;
    }

    /**
 * Initializes an empty bag.
 */
    public Bag() {
        first = null;
        N = 0;
    }

    /**
 * Is this bag empty?
 * @return true if this bag is empty; false otherwise
 */
    public bool isEmpty() {
        return first == null;
    }

    /**
 * Returns the number of items in this bag.
 * @return the number of items in this bag
 */
    public int size() {
        return N;
    }

    /**
 * Adds the item to this bag.
 * @param item the item to add to this bag
 */
    public void Add(Item item) {
        Node<Item> oldfirst = first;
        first = new Node<Item>();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    public Item Get(int i)
    {
        return ((ListIterator<Item>)GetEnumerator ())[i];
    }

    public Item this[int i]
    {
        get {
            return ((ListIterator<Item>)GetEnumerator ())[i];
        }
    }
    /**
 * Returns an iterator that iterates over the items in the bag in arbitrary order.
 * @return an iterator that iterates over the items in the bag in arbitrary order
 */
    public IEnumerator<Item> GetEnumerator()  {
        return new ListIterator<Item>(first);  
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator<T> : IEnumerator<T> {
        private Node<T> current;
        private Node<T> first;

        public ListIterator(Node<T> first) {
            this.first = first;
            current = first;
        }

        public T GetEnumerator() {
            if (!MoveNext ())
                throw new Exception ("No such element");
            T item = current.item;
            //current = current.next; 
            return item;
        }

        public T this[int index]
        {
            get {
                Node<T> temp = first;
                for (int i = 0; i < index; i++) {
                    temp = temp.next;
                }
                return temp.item;
            }
        }
        public T Current
        {
            get { return current.item; }
        }

        object IEnumerator.Current
        {
            get { return Current; }
        }

        public void Dispose()
        {
            current = null;
        }

        public void Reset()
        {
            current = first;
        }

        public bool MoveNext()
        {
            bool res = (current != null);
            current = current.next;
            return (res);
        }
    }
}

如果您想使其通用,为什么要有T和Item,请尝试使其全部变为T

public class Bag<T> : IEnumerable<T>

You're running into this because the default property name for indexers is Item . 您正在遇到这种情况,因为索引器的默认属性名称是Item

If you had followed the naming guidlines for type parameters and named the type parameter TItem (or just T ), you wouldn't have run into this issue. 如果您遵循类型参数命名准则,并将类型参数命名为TItem (或仅命名为T ),则不会遇到此问题。

But in case you really need the type parameter to be called Item , you can change the name of the indexer property using the IndexerName attribute : 但是,如果确实需要将类型参数称为Item ,则可以使用IndexerName属性更改indexer属性的名称:

public class Bag<Item> : IEnumerable<Item>
{
    ...
    [IndexerName("MyIndexer")]
    public Item this[int i]
    {
        get
        {
            return ((ListIterator<Item>)GetEnumerator ())[i];
        }
    }
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Unity 2d 中修复此错误 (CS0102) - How can I fix this error (CS0102) in Unity 2d 运行 ASP.NET 应用程序时出现 CS0102 错误 - CS0102 error while running ASP.NET application CS0102类型&#39;A&#39;已经包含&#39;set_color&#39;的定义 - CS0102 The type 'A' already contains a definition for 'set_color' 如何将cs文件添加到现有C#项目? - How do I add a cs file to an existing C# project? 为什么在 C# 10 中我在初始化属性上收到编译器警告/错误 CS8618 - Why in C# 10 do I get a compiler warning/error CS8618 on init properties xamarin主从页面CS0102和CS0229 - xamarin master-detail page CS0102 nand CS0229 Xamarin Android Java 绑定库.aar CS0102 类型“EventEventArgs”已包含“p0”的定义 - Xamarin Android Java Bindings Library .aar CS0102 The type 'EventEventArgs' already contains a definition for 'p0' 添加自定义属性时如何删除 CS0649 编译器警告? - How do I remove the CS0649 compiler warning when I add a custom attribute? 如何在 C# 中找到生成的“索引器”代码? - How do I find the generated “indexer” code in C#? 如何在 C# 中的索引器参数上设置 convertHighWaterMarkToRowVersion? - How do I set convertHighWaterMarkToRowVersion on the indexer parameters in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM