在網(wǎng)上看到這篇關(guān)于for循環(huán)文章,介紹給大家看看: for循環(huán)的一般結(jié)構(gòu):
for (int i = 0; i < 100; i++) { Console.WriteLine(i); }
遞減的循環(huán):
for (int i = 100; i > 0 ; i--) { Console.WriteLine(i); } 但for當(dāng)然不止這樣一種用法。for的定義,()內(nèi)的三段表達(dá)式,除了中間的必須產(chǎn)生布爾型,并未對(duì)其余兩段有所限制,只要是表達(dá)式就可以了。在Lucene.Net中就有好幾次這樣的用法。例如:
for (Token token = input.Next(result); token != null; token = input.Next(result)) { int len = token.TermText().Length; if (len >= min && len <= max) { return token; } } 這個(gè)語(yǔ)句和下面代碼的效果是一樣的:
Token token; while((token = input.Next(result)) != null) { int len = token.TermText().Length; if (len >= min && len <= max) { return token; } } 其實(shí)我認(rèn)為在這兩種循環(huán)中,第二種比第一種好理解一點(diǎn)。
還有這種
for (i = 75; i-- > 0; ) jjrounds[i] = 0x80000000;
出了一個(gè)空表達(dá)式,呵呵。其實(shí)理解一下也很簡(jiǎn)單,和下面代碼的效果一樣:
for (i = 75; i > 0; i--) jjrounds[i] = 0x80000000;
空表達(dá)式,也是一個(gè)表達(dá)式啊,放在這里也不犯法。
嘿嘿,還有其他的表達(dá)式,比如:
for (int i = 0; i < length; i++, pos++)
這個(gè)應(yīng)該不難理解,第三個(gè)表達(dá)式有兩個(gè),第一個(gè)當(dāng)然也可以有兩個(gè)
比如 for (int i = 100, j = 100; i > 0 ; i--,j++)
中間的表達(dá)式要想用兩個(gè)就要加運(yùn)算符了for (int i = 100, j = 100; i > 0 || j>0 ; i--,j++)
這樣就總結(jié)出三種for循環(huán)樣式
1、for(int i = 0;i < 100;i++) //遞減和遞加的算一種
2、for(;true;) //有空表達(dá)式的
3、for (int i = 100, j = 100; i > 0 || j>0 ; i--,j++) //有多表達(dá)式的
好像就這么多了。但是還有一種,我無法理解的表達(dá)式
for(;;)這是個(gè)死循環(huán),汗!!!廬山瀑布汗啊,反正我理解不了。
嘿嘿,理解上面的表達(dá)式,基本上看別人的代碼就不會(huì)摸不著頭腦了。那是不是真的沒有了呢?
來試試這種
static void Main(string[] args) { for (Act(); ; ) {
} Console.Read(); }
static void Act() {
}
哈哈,真是徹底被打敗了。注意:沒見過有這么用的,純粹是實(shí)驗(yàn),應(yīng)用產(chǎn)生的后果我不負(fù)責(zé)啊。
放上三個(gè)方法爽爽:
static void Main(string[] args) { for (Act1(); Act2(); Act3()) {
} Console.Read(); }
static void Act1() {
}
static bool Act2() { return true; }
static bool Act3() { return true; }
當(dāng)然,你非要用個(gè)委托,我也沒意見:
delegate void Bind(); class Program { static void Main(string[] args) { Bind b = new Bind(Act1); for (b(); Act2(); Act3()) {
} Console.Read(); }
static void Act1() {
}
static bool Act2() { return true; }
static bool Act3() { return true; } } delegate void Bind(); class Program { static event Bind bindEvent;
static void Main(string[] args) { Bind b = new Bind(Act1); bindEvent += new Bind(Program_bindEvent); for (b(); Act2(); bindEvent()) {
} Console.Read(); }
static void Program_bindEvent() { }
static void Act1() {
}
static bool Act2() { return true; }
static bool Act3() { return true; } } 看出來了,只要是表達(dá)式,就能使用!除了第二個(gè)表達(dá)式必須為空,或者布爾值外,其他兩個(gè)基本沒什么限制。第二表達(dá)式為空則是死循環(huán)。
|