sunwen教程之----c#進階
(十)
[email protected]
大家好,我是sunwen.今天下午得知,晚上要去當"更夫".呵呵,我們這個學校很是奇怪,要叫我們輪流去通宵巡邏,從晚上10:30到早上6:00.我有一個物理系的朋友,上次在田家炳樓門前找了一個宣傳板,墊在下面就睡了一覺,聽了笑死我了!哈哈!
現在我想說的是c#中的容器.這是一個非常重要的話題,因為不管你寫什么樣的程序,你都不能不與容器打交道.什么是容器呢(倒!).容器就是可以容納東西的東西(再倒!),在c#和java這種面向對象的編程語言中,容器就被稱為可以容納對象的東東,不是說"一切都是對象嗎?"以前,我一個搞c++的程序員朋友告訴我,java中的容器太好用了,比c++好用多了.而作為java的后來者的c#毫無疑問,它的容器功能肯定也是很強大的.
foreach語句是遍歷容器的元素的最簡單的方法.我們可以用system.collections.ienumerator類和system.collections.ienumerable接口來使用c#中的容器,下面有一個例子,功能是字符串分割器.
000: // collectionclasses/tokens.cs
001: using system;
002: using system.collections;
003:
004: public class tokens : ienumerable
005: {
006: private string[] elements;
007:
008: tokens(string source, char[] delimiters)
009: {
010: elements = source.split(delimiters);
011: }
012:
013: //引用ienumerable接口014:
015: public ienumerator getenumerator()
016: {
017: return new tokenenumerator(this);
018: }
019:
020:
021:
022: private class tokenenumerator : ienumerator
023: {
024: private int position = -1;
025: private tokens t;
026:
027: public tokenenumerator(tokens t)
028: {
029: this.t = t;
030: }
031:
032: public bool movenext()
033: {
034: if (position < t.elements.length - 1)
035: {
036: position++;
037: return true;
038: }
039: else
040: {
041: return false;
042: }
043: }
044:
045: public void reset()
046: {
047: position = -1;
048: }
049:
050: public object current
051: {
052: get
053: {
054: return t.elements[position];
055: }
056: }
057: }
058:
059: // 測試060:
061: static void main()
062: {
063: tokens f = new tokens("this is a well-done program.", new char[] {' ','-'});
064: foreach (string item in f)
065: {
066: console.writeline(item);
067: }
068: }
069: }
這個例子的輸出是:
this
is
a
well
done
program.
好了,這一節就說到這了.現在環境不太好,旁邊一大幫同學在看vcd,不好搞.
下一頁