[英]How do I get rid of this goto?
我剛剛開始了一個職位,在工作日結束時,我通過慢慢閱讀我們的代碼庫來等待流量。 我偶然發現這一點,即使在白板上花了相當多的時間,我仍然無法想到提取goto
。 有沒有辦法消除這種跳躍?
public void MyUpdate(MyType foo)
{
/*Prep code for the loops*/
foreach (Thing bar in something)
{
foreach (Collection item in bar.Stuff)
{
Data dataRX = item.First;
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
goto exitLoops;
}
}
}
exitLoops: ;
}
由於標簽exitLoops
位於方法的末尾,因此您只需使用return
退出方法,如下所示:
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
return;
}
另一種方法是使用這樣的標志:
bool done = false;
foreach (Thing bar in something)
{
foreach (Collection item in bar.Stuff)
{
Data dataRX = item.First;
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
done = true;
break;
}
}
if(done)
break;
}
即使標簽后面有一些代碼,您也可以使用第二種方法。
將內循環移動到方法,並根據其返回值有條件地中斷。
它不是那么好,但沒有實現一個完整的新算法,這似乎是最簡單的方法:
foreach (Thing bar in something)
{
bool exitLoop = false;
foreach (Collection item in bar.Stuff)
{
Data dataRX = item.First;
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
exitLoop = true;
break;
}
}
if (exitLoop) break;
}
或者,您可以使用LINQ執行此操作:
public void MyUpdate(MyType foo)
{
Thing dummy = something.FirstOrDefault(bar => bar.Stuff.SkipWhile((item) =>
{
Data dataRx = item.First;
if (dataRx != null && dataRx.ID.Equals(globalNonsense.ID))
{
dataRx.fooBuddy = foo;
return false;
}
else
{
return true;
}
}).Count() != 0);
}
如果你使用foreach
你將需要break
或return
。 但沒有break
, return
或goto
有這個選項:
public void MyUpdate(MyType foo)
{
bool stop = false;
/*Prep code for the loops*/
for (var i = 0; !stop && (i < something.Count); i++)
{
for (var j = 0; !stop && (j < something[i].Stuff.Count); j++)
{
Data dataRX = something[i].Stuff[j].First;
if (dataRX != null && dataRX.ID.Equals(globalNonsense.ID))
{
// Update Data with the latest changes
dataRX.fooBuddy = foo;
stop = true;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.