我正在尝试退出using语句,同时保持封闭的for循环.例如.
for (int i = _from; i <= _to; i++)
{
try
{
using (TransactionScope scope = new TransactionScope())
{
if (condition is true)
{
// I want to quit the using clause and
// go to line marked //x below
// using break or return drop me to line //y
// outside of the for loop.
}
}
} //x
}
//y
Run Code Online (Sandbox Code Playgroud)
我已经尝试过使用break来解决这个问题,但是我希望保持在// x的for循环中,以便for循环继续处理.我知道我可以通过抛出异常并使用catch来实现它,但是如果有一种更优雅的方法来突破使用,我宁愿不做这个相对昂贵的操作.谢谢!
完全省略使用:
if (condition is false)
{
using (TransactionScope scope = new TransactionScope())
{
....
Run Code Online (Sandbox Code Playgroud)
没有必要跳出一个using块,因为 using 块不会循环。你可以简单地失败到最后。如果有您不想执行的代码,请使用if-clause跳过它。
using (TransactionScope scope = new TransactionScope())
{
if (condition)
{
// all your code that is executed only on condition
}
}
Run Code Online (Sandbox Code Playgroud)
正如@Renan所说,您可以使用!运算符并根据条件反转布尔结果。您还可以使用continueC# keyworkd 转到循环的下一项。
for (int i = _from; i <= _to; i++)\n{\n\xc2\xa0 \xc2\xa0 try\n\xc2\xa0 \xc2\xa0 {\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 using (TransactionScope scope = new TransactionScope())\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 {\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 if (condition is true)\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 {\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 // some code\n\xc2\xa0\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 continue; // go to next i\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 }\n\xc2\xa0 \xc2\xa0 \xc2\xa0 \xc2\xa0 }\n\xc2\xa0 \xc2\xa0 }\n}\nRun Code Online (Sandbox Code Playgroud)\n