当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - if else if in while loop were else if test is defined in the first cycle

问题描述:

Somewhat confusing, especially when trying to describe in a title. Here's some example code. I'm hoping this is possible (I haven't found a way to do it just yet.)

 DateTime startTime = DateTime.Now;

int i = 0;

bool running = true;

while (running)

{

DateTime? lastRunTime = null;

if (i == 0)

{

if ((DateTime.Now - startTime).Minutes >= Program.genTimer)

{

i = 1;

lastRunTime = DateTime.Now;

}

}

else if ((DateTime.Now - lastRunTime).Minutes >= Program.genTimer)

{

//doestuff

}

This probably looks foolish (and this does not work at all, the obvious being a nullable timespan doesnt contain a definition for 'Minutes. I've also tried

DateTime lastRunTime;

instead of

DateTime? lastRunTime = null;

So basically I'm forcing the first if statement to be true the first time and false for every pass afterward. I'm definitely open to a different approach.

If you're curious, the goal is to run this in a service where it runs through 11 operations one at a time on different time intervals. Due to how these operations are processed, I can't have more then one run at a time.

网友答案:

If you're using a nullable DateTime, you probably don't need i at all. .HasValue will tell you if it's been set or not. Which will only be false the first time. Also move it out of the while loop, otherwise you're redeclaring it each time.

Try something like

DateTime startTime = DateTime.Now;
bool running = true;
DateTime? lastRunTime = null;
while (running)
{
    if (!lastRunTime.HasValue)
    {
        if ((DateTime.Now - startTime).Minutes >= Program.genTimer)
        {
            lastRunTime = DateTime.Now;
        }
    }
    else if ((DateTime.Now - lastRunTime.Value).Minutes >= Program.genTimer)
    {
            //doestuff
    }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: