首页 > 解决方案 > 如何在 C# for 循环中使用 var?

问题描述

我试图学习编程并从基础开始,但无法弄清楚。我试图使用我的用户输入 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");
            }
        }
    }
}

标签: c#for-loop

解决方案


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

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");
            // }
        }
    }
}

推荐阅读