List<string> str = new List<string>(); str.Add( "zs"); str.Add("ls"); str.Add( "ws" ); foreach(string s in str) { str.Remove(s); }
有時候我們在foreach中需要修改或者刪除集合
可是這時候卻報如下錯誤:集合已修改;可能無法執行枚舉操作。
其實我們簡單實現以下就可以實現這個功能
直接上代碼如下
public class MyClass<T> { MyClassCollection<T> collection = new MyClassCollection<T>(); public IEnumerator GetEnumerator() { return collection; } public void Remove(T t) { collection.Remove(t); } public void Add(T t) { collection.Add(t); } } public class MyClassCollection<T> : IEnumerator { List<T> list = new List<T>(); public object current = null; Random rd = new Random(); public object Current { get { return current; } } int icout = 0; public bool MoveNext() { if (icout >= list.Count) { return false; } else { current = list[icout]; icout++; return true; } } public void Reset() { icout = 0; } public void Add(T t) { list.Add(t); } public void Remove(T t) { if (list.Contains(t)) { if (list.IndexOf(t) <= icout) { icout--; } list.Remove(t); } } } public class MyItem { public string id { get; set; } public int sex { get; set; } public string name { get; set; } public int age { get; set; } }
然后我們直接調用一下試驗下:
MyClass<MyItem> myclass = new MyClass<MyItem>(); //添加10條數據 Random rd = new Random(); for (int i = 0; i < 10; i++) { MyItem item = new MyItem(); item.age = rd.Next(1, 80); item.id = rd.Next().ToString(); item.name = "name" + rd.Next().ToString(); item.sex = rd.Next(0, 1); myclass.Add(item); } foreach (MyItem item in myclass) { Console.WriteLine(item.name); myclass.Remove(item); } Console.Read();
這段代碼就是模擬10條數據 輸出信息后直接刪除
哈哈 是不是很簡單呢?當然要實現修改或者其他的功能也是類似的
另外IEnumerator接口中的 public object Current 為引用類型 所以 如果這里MyItem如果修改為基本類型的話肯定會出現拆箱裝箱
如果 如果foreach中是基本類型的話就不要用foreach了 如果需要考慮性能的話。
源代碼下載:https://files.cnblogs.com/files/devgis/TestIEnumerator.rar