【问题标题】:C# Use variable from loop in next loop runC#在下一个循环运行中使用来自循环的变量
【发布时间】:2017-09-06 02:08:43
【问题描述】:

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

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

 double result = (valuebefore - valuecurrent); 
}

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

提前致谢! 蒂姆

【问题讨论】:

  • 将其存储在循环外的变量中..
  • 我认为您可以使用另一个变量并在每个循环结束时将其设置为 valueCurrent

标签: c# winforms while-loop


【解决方案1】:
        // 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 逻辑来保存第一个值,然后减去后续值。

【讨论】:

    【解决方案2】:

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

    var valuebefore = 0;
    
    while(true)
    {
     valuecurrent = webclient.DownloadString("http://ipadress/value");
    
     double result = (valuebefore - valuecurrent);
    
     valuebefore = valuecurrent;
    }
    

    【讨论】:

    • 抱歉询问。这真的很容易,但我不知道t thought about this option because it was too easy and I thought that it wont work. I dont 知道为什么。谢谢!
    • 感谢您分别输入 'valuebefore' 作为 var,很多人会使用不可变的 double
    • @MadMyche, var valuebefore = 0; 将初始化 int 类型的变量
    • 我只是展示了他正在寻找的基本示例。由他决定他想要的数据类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2019-03-06
    • 2017-11-29
    • 2022-01-04
    • 2022-11-03
    • 1970-01-01
    • 2021-03-07
    相关资源
    最近更新 更多