多次调用方法

San*_*eep -3 .net c#

int noOfAttempts = 3;
void StartServer();
bool IsServerRunning();
Run Code Online (Sandbox Code Playgroud)

我需要StartServer()根据结果重新尝试3次IsServerRunnig().像这样的东西:

StartServer();
if (!IsServerRunning())
{
    StartServer();
    if (!IsServerRunning())
    {
        StartServer();
        if (!IsServerRunning())
        {
            StartServer();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我不想使用for循环或像上面那样丑陋的代码.有没有更好的方法呢?一种方式,如果noOfAttempts将来改变,我将不必更改我的代码?

编辑: 我期待"委托"概念(如果可能的话).

Jon*_*lor 7

你可以使用while循环

int counter = 0;
while(counter < 3 && !IsServerRunning()) {
    StartServer();
    counter++;
}
Run Code Online (Sandbox Code Playgroud)


tuk*_*aef 7

UPD:

好像你实际上想要(编辑)一些简洁的方法来描述重试逻辑.在这种情况下,请查看瞬态故障处理库,例如Polly.


好.

3.TimesUntil(IsServerRunning, StartServer); 
Run Code Online (Sandbox Code Playgroud)

在这里代表魔术:

public static class Extensions 
{
    public static void TimesWhile(this int count, Func<bool> predicate, Action action)
    {
        for (int i = 0; i < count && predicate(); i++) 
           action();
    }
    public static void TimesUntil(this int count, Func<bool> predicate, Action action)
    {
        for (int i = 0; i < count && !predicate(); i++) 
            action();
    }
}
Run Code Online (Sandbox Code Playgroud)

尊敬的downvoters: 这只是为了好玩,我永远不会为真正的项目编写这些代码.


Ala*_*lan 6

在这里你没有循环......

private void Start(int numberOfAttempts)
{
    if (numberOfAttempts == 0)
        return;

    StartServer();

    if (!IsServerRunning())
        Start(numberOfAttempts-1);
}
Run Code Online (Sandbox Code Playgroud)

  • 使它成为`Start( - numberOfAttempts)`或`Start(numberOfAttempts-1)`否则你将面临无限递归. (6认同)