索引器實現for迴圈
console.readkey();
}
}public class people
}//索引器
public string this[int index]
set
}}}
列舉器實現foreach
foreach (string p in people)
console.readkey();
}
}public class people : ienumerable
}//索引器
public string this[int index]
set
}// 類裡有getenumerator()就能實現foreach,可以不繼承 ienumerable 介面
public ienumerator getenumerator()
其實有下面這個迭代器就可以了,用yield return,編譯器會幫忙生成列舉器
//public ienumerator getenumerator()
////}
}//列舉器
public class peopleenumerator : ienumerator
public object current
else}}
public bool movenext()
index = -1;
return false;
}public void reset()
}} ** ienumerator泛型介面;foreach中var能否型別推斷的解釋**
如圖,將上面**的foreach (string p in people)中的string改為var,推斷var為object型別
這是列舉中**
的返回是objectpublic object current
else}}
列舉器實現ienumerator介面就可以使var能推斷出想要的型別了,主要就兩點變化,見注釋
**如下
顯示實現介面可以參考:public class people/*:ienumerable*/
}public string this[int index]
set
}// 這個類就不繼承ienumerator介面了,getenumerator()方法直接返回ienumerator就ok,如果繼承ienumerator,因為ienumerator還繼承了ienumerator,還得多寫兩個顯示實現的方法
public ienumeratorgetenumerator()
////ienumerator ienumerable.getenumerator()//}
//列舉器得繼承泛型介面
public class peopleenumerator : ienumerator
public string current
}object ienumerator.current
}public void dispose()
public bool movenext()
index = -1;
return false;
}public void reset()
}
ps:hashtable的foreach裡的var不能型別推斷,dictionary的可以就是這個原因
,所以hashtable一般 foreach (dictionaryentry h in hash){},這樣h才能 . 出key。
而dictionary 用 foreach(var d in dic ) ,d就能 . 出key。
** icomparable比較器**
實現icomparable介面的compareto方法。
C 迭代器,列舉器
測試 using system using system.collections.generic using system.linq using system.text using system.collections namespace 07迭代器 private int move 0 const...
C 列舉器和迭代器
using system using system.collections namespace study public class people ienumerable 宣告可列舉類 ienumerator ienumerable.getenumerator 實現ienumerable的geten...
C 迭代器和列舉器01
1 ienumerable 提供可列舉的能力,只有實現該介面才可以使用foreach物件迭代物件 其介面包含的方法 ienumerator getenumerator 該介面中包含實現迭代提供的值序列或者自定義值序列,然後對其進行迭代 public class test public class t...