10

我试图退出 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

我曾尝试使用 break,它在 //y 处将我吐出,但是我想留在 //x 处的 for 循环中,以便 for 循环继续处理。我知道我可以通过抛出异常并使用 catch 来做到这一点,但如果有更优雅的方式来打破使用,我宁愿不做这个相对昂贵的操作。谢谢!

4

8 回答 8

8

完全跳过使用:

if (condition is false)
{
    using (TransactionScope scope = new TransactionScope())
    {
....
于 2013-05-16T14:23:23.017 回答
5

没有必要跳出using块,因为 using 块不会循环。你可以简单地跌到最后。如果有您不想执行的代码,请使用 -if子句跳过它。

    using (TransactionScope scope = new TransactionScope())
    {
        if (condition)
        {
            // all your code that is executed only on condition
        }
    }
于 2013-05-16T14:23:55.633 回答
3

只需更改 ,if以便在条件不成立时进入块。然后将其余代码放在该块内。

于 2013-05-16T14:22:04.390 回答
3

正如@Renan 所说,您可以使用!运算符并在条件下反转您的 bool 结果。您还可以使用continueC# keyworkd 转到循环的下一项。

for (int i = _from; i <= _to; i++)
{
    try
    {
        using (TransactionScope scope = new TransactionScope())
        {
            if (condition is true)
            {
                // some code
 
                continue; // go to next i
            }
        }
    }
}
于 2013-05-16T14:24:26.413 回答
1

我会颠倒逻辑并说:

for (int i = _from; i <= _to; i++)
{

    try
    {

        using (TransactionScope scope = new TransactionScope())
        {
            if (condition is false)
            {
                // in here is the stuff you wanted to run in your using
            }
            //having nothing out here means you'll be out of the using immediately if the condition is true
        }

    } //x
}
//y

另一方面,如果您按照 Dave Bish 的建议完全跳过 using ,您的代码将执行得更好,因为在您不希望 using 的情况下,您不会创建一个对象只是对它不做任何事情......

于 2013-05-16T14:23:20.803 回答
0

我只是想知道同样的事情。给出的答案都不适合我的情况。然后我想通了:

异常通常是出现严重错误的迹象。它们也可用于基本的流量控制。

for (int i = _from; i <= _to; i++)
 {

    try
    {

        using (TransactionScope scope = new TransactionScope())
        {
            if (condition is true)
            {
                throw new Exception("Condition is true.");
            }
        }

    } 
    catch(Exception exception)
    {
        Console.WriteLine(exception.Message);
    }//x
}
//y
于 2019-05-17T01:44:52.397 回答
0

您可以使用标签,并使用goto label来跳出 using(() 语句。

using (var scope = _services.CreateScope())
{
    if (condition) {
        goto finished;
    }
}

finished:
// continue operation here
于 2020-04-07T15:58:58.547 回答
-1

您是否尝试过使用

continue;

?

于 2013-05-16T14:26:48.523 回答