2 回答

TA貢獻1770條經(jīng)驗 獲得超3個贊
嗯,goto
但這很難看,并不總是可能的。您還可以將循環(huán)放入方法(或anon-method)并用于return
退回到主代碼。
// goto for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { goto Foo; // yeuck! } }Foo: Console.WriteLine("Hi");
VS:
// anon-methodAction work = delegate{ for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { return; // exits anon-method } }};work(); // execute anon-methodConsole.WriteLine("Hi");
請注意,在C#7中我們應(yīng)該得到“本地函數(shù)”,其中(語法tbd等)意味著它應(yīng)該工作如下:
// local function (declared **inside** another method)void Work(){ for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { return; // exits local function } }};Work(); // execute local functionConsole.WriteLine("Hi");

TA貢獻1780條經(jīng)驗 獲得超4個贊
C#自適應(yīng)方法經(jīng)常用于C - 外部循環(huán)變量的設(shè)置值在循環(huán)條件之外(即對于循環(huán)使用int變量INT_MAX -1
通常是不錯的選擇):
for (int i = 0; i < 100; i++){ for (int j = 0; j < 100; j++) { if (exit_condition) { // cause the outer loop to break: // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue i = int.MaxValue - 1; Console.WriteLine("Hi"); // break the inner loop break; } } // if you have code in outer loop it will execute after break from inner loop }
正如代碼中的注釋所說,break
不會神奇地跳轉(zhuǎn)到外循環(huán)的下一次迭代 - 所以如果你有內(nèi)循環(huán)之外的代碼,這種方法需要更多的檢查。在這種情況下考慮其他解決方案
這種方法適用于for
和while
循環(huán),但不起作用foreach
。如果foreach
你沒有代碼訪問隱藏的枚舉器,所以你不能改變它(即使你可能IEnumerator
沒有一些“MoveToEnd”方法)。
對內(nèi)聯(lián)評論作者的致謝: Meta的i = INT_MAX - 1
建議/ ygoe的評論。 正確的jmbpiano通過內(nèi)部循環(huán)后約代碼備注blizpasta for
foreach
IntMax
- 2 回答
- 0 關(guān)注
- 356 瀏覽
添加回答
舉報