C#在下一个循环运行中使用循环变量

时间:2017-04-10 21:31:16

标签: c# winforms while-loop

我的winforms应用程序出了问题,但我找不到解决问题的方法:我正在运行一个从Web服务器获取值的while循环。 然后,该值应该从之前运行的循环获取的值中减去。

while(true)
{
 valuecurrent = webclient.DownloadString("http://ipadress/value");

 double result = (valuebefore - valuecurrent); 
}

有没有办法保存之前运行的值并在下一次循环运行中使用它?

提前致谢! 添

2 个答案:

答案 0 :(得分:2)

只需在循环之外/之前添加一个变量,并在每次传递时设置它。

var valuebefore = 0;

while(true)
{
 valuecurrent = webclient.DownloadString("http://ipadress/value");

 double result = (valuebefore - valuecurrent);

 valuebefore = valuecurrent;
}

答案 1 :(得分:0)

        // Assign a null value before
        double? valuebefore = null;
        while (true)
        {
            // Get the current value from the webserver
            valuecurrent = webclient.DownloadString("http://ipadress/value");

            // Use the current value if we don't have any previous values
            // Subtract the current value from previous value if it exists
            double result = valuebefore.HasValue == false
                ? valuecurrent
                : valuebefore.Value - valuecurrent;

            // Save the result to our value before to be used in next loop
            valuebefore = result;
        }

您可以利用可空类型和简单的if / then逻辑来保存第一个值,然后减去后续值。