3 回答

TA貢獻1859條經驗 獲得超6個贊
如果您選擇使用通用集合(例如List<MyObject>而不是)ArrayList,則會發現List<MyObject>會同時提供您可以使用的通用和非通用枚舉器。
using System.Collections;
class MyObjects : IEnumerable<MyObject>
{
List<MyObject> mylist = new List<MyObject>();
public MyObject this[int index]
{
get { return mylist[index]; }
set { mylist.Insert(index, value); }
}
public IEnumerator<MyObject> GetEnumerator()
{
return mylist.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}

TA貢獻1880條經驗 獲得超4個贊
您可能不想要顯式的實現IEnumerable<T>(這就是您所顯示的)。
通常的模式是使用IEnumerable<T>的GetEnumerator在明確的執行IEnumerable:
class FooCollection : IEnumerable<Foo>, IEnumerable
{
SomeCollection<Foo> foos;
// Explicit for IEnumerable because weakly typed collections are Bad
System.Collections.IEnumerator IEnumerable.GetEnumerator()
{
// uses the strongly typed IEnumerable<T> implementation
return this.GetEnumerator();
}
// Normal implementation for IEnumerable<T>
IEnumerator<Foo> GetEnumerator()
{
foreach (Foo foo in this.foos)
{
yield return foo;
//nb: if SomeCollection is not strongly-typed use a cast:
// yield return (Foo)foo;
// Or better yet, switch to an internal collection which is
// strongly-typed. Such as List<T> or T[], your choice.
}
// or, as pointed out: return this.foos.GetEnumerator();
}
}

TA貢獻1818條經驗 獲得超11個贊
請注意,另一種已IEnumerable<T>實現的System.Collections方法是MyObjects從類派生您的類System.Collections作為基類(documentation):
System.Collections:提供通用集合的基類。
我們以后可以使我們自己實行重寫虛擬System.Collections方法,以提供定制的行為(僅適用于ClearItems,InsertItem,RemoveItem,和SetItem沿Equals,GetHashCode以及ToString從Object)。不同于,List<T>后者的設計不容易擴展。
例:
public class FooCollection : System.Collections<Foo>
{
//...
protected override void InsertItem(int index, Foo newItem)
{
base.InsertItem(index, newItem);
Console.Write("An item was successfully inserted to MyCollection!");
}
}
public static void Main()
{
FooCollection fooCollection = new FooCollection();
fooCollection.Add(new Foo()); //OUTPUT: An item was successfully inserted to FooCollection!
}
請注意,collection僅在需要自定義收集行為的情況下才建議使用這種驅動,這種情況很少發生。見用法。
- 3 回答
- 0 關注
- 607 瀏覽
添加回答
舉報