在这种情况下使用"goto"是否可以接受?

kof*_*cii 1 c# coding-style goto

以下是伪代码:

myGoto:
try
{
   // do some db updating
   myDB.doOptimisticConcurrency();

} catch (MyConcExeption ex) {

   if (tried < fiveTimes) {
       myDB.Refresh();
       tried++;
       goto myGoto;
   }

}
Run Code Online (Sandbox Code Playgroud)

我在一个方法中有几个try-catch块,我不想从一开始就为每个抛出的异常重新调用我的方法.goto在这种情况下使用是否可接受?

Gio*_*rgi 16

您可以将其更改为:

while (tried < fiveTimes)
try
{
   // do some db updating
   myDB.doOptimisticConcurrency();
   break;
}
catch (MyConcExeption ex)
{
   tried++;
   myDB.Refresh();
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 13

我不会使用"goto" - 但你可能想写一个小帮手方法.例如:

public static void TryMultiple<E>(Action action, int times) where E : Exception
{
    E lastException = null;
    for (int i = 0; i < times; i++)
    {
        try
        {
            action();
            return; // Yay, success!
        }
        catch (E exception)
        {
            // Possibly log?
            lastException = exception;
        }
    }
    throw new RetryFailedException("Retry failed " + times + " times",
                                   lastException);
}
Run Code Online (Sandbox Code Playgroud)

这只是解决方案的草图 - 您需要相应地调整它.无论如何,这基本上允许您以可重用的方式在半被接受的异常面前执行重试.您可能会使用lambda表达式来表达操作,或者有时只使用单个方法调用的方法组:

TryMultiple<MyConcurrencyException>(myDB.doOptimisticConcurrency, 5);
Run Code Online (Sandbox Code Playgroud)