【问题标题】:How can I use a var in a C# for loop?如何在 C# for 循环中使用 var?
【发布时间】:2021-07-23 11:16:51
【问题描述】:

我正在尝试学习编程并从基础开始,但无法弄清楚。 我正在尝试使用我的用户输入 var 数量并获取用户输入文本值并在 for 循环中使用它。

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("URL To ICMP: ");
        var url = System.Console.ReadLine();

        System.Console.WriteLine("How many times do you want to ping " + url + "?");
        var amount = System.Console.ReadLine();

        Ping myPing = new Ping();
        PingReply reply = myPing.Send(url);

        for (int i = 0; i < amount; i = i + 1)
        {
            System.Console.WriteLine();
            if (i = amount)
            {
                break;
                System.Console.WriteLine("\nFinished ICMP");
            }
        }
    }
}

【问题讨论】:

  • Ping 部分不应该进入 for 循环吗?毕竟你想重复那个动作特定的次数
  • 不应该 if(i=amount)if(i==amount) 吗?使用=,您不会循环太多,因为您将在第一次迭代期间达到退出条件。但是我觉得您的代码不会编译,因为您尝试将 int (i) 与 string (amount) 进行比较
  • 整个 if (i == amount) {...} 毫无意义。 'i' 永远不会等于 'amount' 因为循环仅在 'i' 小于 'amount' 时运行。
  • 还有:amountstringiint;他们永远不会平等;考虑int.Parse / int.TryParse string
  • 附带说明,如果您在 Windows 服务器上进行开发:曾经调试 Ping 可能会使您的服务器崩溃。不确定该错误是否仍然存在,但我发现了困难的方式。

标签: c# for-loop


【解决方案1】:

您的代码有一些问题。不过,要首先回答您的问题,您需要将 ping 向下移动到循环中。其余的我会用 cmets 记下:

class Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("URL To ICMP: ");
        var url = System.Console.ReadLine();

        // Use String.Format instead of concatenation.
        System.Console.WriteLine(String.Format("How many times do you want to ping {0}?", url));
        var amount = System.Console.ReadLine();
        int count;
        if(!int.TryParse(amount, out count)) // You should attempt to convert to integer.
        {
            // If invalid, notify user and return.
            Console.WriteLine("Invalid number!");
            return;
        }
        Ping myPing = new Ping();
        for (int i = 0; i < count; i++) // use the `count` variable.
        {
            System.Console.WriteLine(String.Format("Pinging host: {0}...", url));
            // You can use PingReply below to write the response
            // If you do not plan to use that, I would omit the set here
            // and just use `myPing.Send(url);`
            PingReply reply = myPing.Send(url);

            // This next section you do not need as the loop will automatically break 
            // after the set number of iterations.
            // if (i = amount) // this should actually be  `==` instead of `=`
            // {
            //     break;
            //     System.Console.WriteLine("\nFinished ICMP");
            // }
        }
    }
}

【讨论】:

  • String interpolation 可以比Format 更好(更具可读性),例如$"How many times do you want to ping {url}?"
  • 我可以使用的最多 ping 数是多少?
  • 作为integer (Int32),最大值为2147483647
猜你喜欢
  • 1970-01-01
  • 2012-05-19
  • 2021-10-26
  • 2015-08-28
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
相关资源
最近更新 更多