![](/img/trans.png)
[英]Why is it necessary to implement IEnumerator when Implementing IEnumerable
[英]implement IEnumerator and IEnumerable in ICollection
我对ICollection的东西很陌生,并且需要一些有关如何实现IEnumerable和IEnumerator的指导。 我已经检查了Microsoft文档,我想我明白那里的意思(我认为)。 但是,当我尝试以我的情况实施它时,我有点困惑,可能需要澄清一下。
基本上,我声明了一个类T,然后声明了另一个实现ICollection的类Ts。 在Ts,我有一本字典。
在主程序中,我想这样初始化类Ts:Ts ts = new Ts(){{a,b},{c,d}};
因此,我的问题是:
1)这样做合法吗? 似乎是编译器没有抱怨,尽管我没有运行测试,因为我没有彻底实现IEnumerable和IEnumerator,这给我的第二个问题带来了麻烦
2)如何实现IEnumerable和IEnumerator?
以下是我的伪代码来说明我的观点。
public class T
{
string itemName;
int quantity;
.....
public T(string s, int q)
{
.....
}
}
public class Ts: ICollection
{
private Dictionary<string, T> inventory= new Dictionary<string,T>();
public void Add(string s, int q)
{
inventory.Add(s, new T(s,q));
}
public IEnumerator<T> GetEnumerator()
{
// please help
}
IEnumerator IEnumerable.GetEnumerator()
{
// what is the proper GetEnumerator here
}
...
implement other method in ICollection
}
extract from the main program
public Ts CollectionOfT = new Ts(){{"bicycle",100},{"Lawn mower",50}};
.........
正确的实现是在显式实现中将您的集合转换为IEnumerable
:
IEnumerator IEnumerable.GetEnumerator() {
return ((IEnumerable)your_collection_here).GetEnumerator();
}
对于通用版本,请在您的集合上调用GetEnumerator
:
public IEnumerator<T> GetEnumerator() {
return your_collection_here.GetEnumerator();
}
您必须具有支持自定义集合的东西。例如List
, Array
等。在那些实现中使用它。
老实说,您不需要围绕Dictionary构建自己的集合“包装器”,但如果必须的话,可以将几乎所有的调用委托给字典以实现ICollection接口。 希望这可以帮助
public class Ts: ICollection<T>
{
private Dictionary<string, T> inventory= new Dictionary<string,T>();
//public void Add(string s, int q)
//{
// inventory.Add(s, new T(s,q));
//}
public void Add(T item)
{
inventory.Add(item.ItemName,item);
}
public void Add(string s, int q)
{
inventory.Add(s, new T(s, q));
}
public void Clear()
{
inventory.Clear();
}
public bool Contains(T item)
{
return inventory.ContainsValue(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
inventory.Values.CopyTo(array, arrayIndex);
}
public int Count
{
get { return inventory.Count; }
}
public bool IsReadOnly
{
get { return false; }
}
public bool Remove(T item)
{
return inventory.Remove(item.ItemName);
}
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
return inventory.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return inventory.Values.GetEnumerator();
}
}
class Program
{
Ts ts = new Ts { { "a", 1 }, { "b", 2 } };
foreach (T t in ts)
{
Console.WriteLine("{0}:{1}",t.ItemName,t.Quantity);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.