[英]Statements in the Condition of a While Loop
說我有一個可以通過TheCollection.GetByID(long)
訪問的東西的集合,但是我無法提前獲取東西的長度。 我想建立一個while循環來遍歷每個循環。
顯然,我可以這樣做:
var iter = 0; var thing = TheCollection.GetByID(iter);
while (thing != null) {
dealWithTheThing(thing);
iter++;
thing = TheCollection.GetByID(iter);
}
但是我更喜歡通過將修改放入構造函數中進行整理,並能夠得到如下所示的內容:
var iter = 0; var thing;
while ((thing = TheCollection.GetByID(iter++)) != null) {
dealWithTheThing(thing);
}
這有可能嗎?
是的,您的例子很好。 您可以在一個條件內進行分配,並且樣式非常清晰(至少對我而言)。
雖然在循環條件中使用賦值運算符看起來很漂亮,但可能會給其他人造成混淆,因為很容易將==
=
( 更多信息:搜索“ Assignment Expressions” )
在給您警告之后,我發現以下內容更具可讀性:
var iter = 0; var thing; while (thing = TheCollection.GetByID(iter++) && thing != null) { dealWithTheThing(thing); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.