如何从using语句中退出

11

我正在尝试从一个使用语句中退出,同时仍然保持在包含的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循环中以便继续处理。我知道可以通过抛出异常并使用catch语句来实现,但如果有更优雅的方法退出循环,我宁愿不执行这个相对较昂贵的操作。谢谢!


1
你可以将使用循环的部分放在一个单独的方法中,如果条件为真,则返回。 - Rogue
没错,Servy。没有仔细考虑。已删除。 - Marco
你总是可以将其余的代码用if (condition is false)语句包装在using语句中。 - Murkaeus
8个回答

8

完全跳过使用:

if (condition is false)
{
    using (TransactionScope scope = new TransactionScope())
    {
....

如果条件是数据库/EF等调用的一部分,该怎么办? - Paul Zahra
1
然后只需把它放在里面吗?我们只能根据问题中的内容推荐最佳解决方案... - Dave Bish

5
不需要打破using块,因为using块不会循环。您可以直接跳转到结尾。如果有您不想执行的代码,请使用if子句跳过它。
    using (TransactionScope scope = new TransactionScope())
    {
        if (condition)
        {
            // all your code that is executed only on condition
        }
    }

3

如@Renan所说,您可以使用!运算符并在条件上反转布尔结果。您还可以使用continue C#关键字以访问循环的下一个项目。

for (int i = _from; i <= _to; i++)
{
    try
    {
        using (TransactionScope scope = new TransactionScope())
        {
            if (condition is true)
            {
                // some code
 
                continue; // go to next i
            }
        }
    }
}

我认为最好的答案是这个、我的和 Dave Bish 的混合。如果 OP 能提供更多的见解,我们可以给出更好的答案。无论条件如何,你会在 using 块内做其他事情吗? - Geeky Guy

3

只需更改if,使其在条件不为真时进入该块。然后在该块内编写其余代码。


1
你可以使用标签,并使用goto label跳出using(()语句。
using (var scope = _services.CreateScope())
{
    if (condition) {
        goto finished;
    }
}

finished:
// continue operation here

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的情况下,您不会创建一个对象只是为了什么也不做...


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

-2

你尝试过使用吗?

continue;

?


1
在当前状态下,这可能更适合作为注释。只需提供使用 continue 的示例,而不是提出另一个问题。 - Steven V

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接