【发布时间】:2015-05-17 23:51:50
【问题描述】:
所以我正在尝试将 java Bag 类移植到 C#。我知道我在这里做错了,因为在 foreach 语句中对这段代码的测试只产生了前两个添加的项目,但这不是我的主要问题。
当我尝试将索引器添加到 Bag 类时,编译器会抛出 CS0102,并抱怨 Bag<Item> 已经包含 Item 的定义。但是我可以创建一个方法public Item Get(int i),它做同样的事情就好了。为什么会发生这种情况,如何为此类创建索引器?
编辑确切的错误是:Bag.cs(15,15): Error CS0102: The type Algorithms4e.ch1.Bag<Item>' already contains a definition forItem' (CS0102)
顺便说一句,我知道 Bag 类不应该使用索引器,但它是事物的原理;我应该能够将索引器添加到任何类吧?
如果有帮助的话,我正在 Ubuntu 14.04.2 LTS 下运行 Mono C# 编译器版本 3.2.8.0。
如果你们都需要更多信息,或者我发布的内容是正确的起点,请告诉我。我很乐意更新问题。
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);
}
}
}
【问题讨论】:
-
你能告诉我们确切的错误吗?
-
我在想这可能是编译器中的一个错误?还是太冒昧了?
-
感谢该链接,我的下一个问题是如何使 foreach 语句正常工作,但也许我应该为此发一个新帖子?
标签: c# generics compiler-errors mono indexer