【问题标题】:C# - What does the last while loop and 'var x' do?C# - 最后一个while循环和'var x'做什么?
【发布时间】:2018-02-01 17:28:29
【问题描述】:
using System;

namespace ConsoleApplication1
{
    class Program
    {        
        static void Main()
        {            
            var entry = 0;
            try {
                Console.Write("Enter the number of times to print \"Yay!\": ");
                var entryParsed = int.Parse(Console.ReadLine());

                if (entryParsed < 0) 
                {
                    Console.Write("You must enter a positive number.");
                }  
                else 
                {
                    entry += entryParsed;
                }
            }
            catch (FormatException)
            {
                Console.Write("You must enter a whole number.");
            }

            var x = 0;
            while (true) 
            {
                if (x < entry) 
                {
                    Console.Write("Yay!");
                    x++;
                }
                else
                {
                    break;
                }
            }
        }
    }
}

在最后几行代码中,我不明白 'var x' 和 while 循环的作用或代表什么。此代码示例来自 Treehouse 挑战,但“var x”如何使程序按预期工作?谢谢您的帮助! :)

【问题讨论】:

  • 它将循环打印 'yay' 进入时间。 for 循环会更清晰
  • 使用调试器单步调试代码,你会看到它到底做了什么。
  • x 是一个计数器,在每次打印“Yay”后递增。在 x = entry 之后,while 循环中的逻辑将强制它退出(中断)。如果您发现 while 循环逻辑有点复杂,您可以使用简单的 for 循环。
  • var x 是一个隐式分配的类型计数器变量,它自动将 x 分配给类型int。 while 循环可以用这个 for 循环代替,以 (x - 1) 次打印文本:for (var x = 0; x &lt; entry; x++).

标签: c# loops while-loop var


【解决方案1】:

C# 中的var 关键字表示“推断类型”。

var x = 0; //Means the same thing as latter 
int x = 0; //The compiler actually CONVERTS the former to this in an early pass when it strips away syntactic sugar

您发布的代码非常...暗示初学者。最后一个块是for 循环。无可辩驳。任何替代方案在客观上都是劣等的。

这是另一种编写方式。不可否认,这有点过头了,但你明白了:

using System;
using System.Linq;
using System.Collections.Generic;

namespace Example
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int entry = CollectUserInput<int>("Enter the number of times to print \"Yay!\": ",
                (int x) => x > 0, "Please enter a positive number: ");

            for (int i=0; i<entry; i++) {
                Console.Write("Yay!");
            }
        }

        /// <summary>
        /// Prompts user for console input; reprompts untils correct type recieved. Returns input as specified type.
        /// </summary>
        /// <param name="message">Display message to prompt user for input.</param>
        private static T CollectUserInput<T>(string message = null)
        {
            if (message != null)
            {
                Console.WriteLine(message);
            }
            while (true)
            {
                string rawInput = Console.ReadLine();
                try
                {
                    return (T)Convert.ChangeType(rawInput, typeof(T));
                }
                catch
                {
                    Console.WriteLine("Please input a response of type: " + typeof(T).ToString());
                }
            }
        }

        /// <summary>
        /// Prompts user for console input; reprompts untils correct type recieved. Returns input as specified type.
        /// </summary>
        /// <param name="message">Display message to prompt user for input.</param>
        /// <param name="validate">Prompt user to reenter input until it passes this validation function.</param>
        /// <param name="validationFailureMessage">Message displayed to user after each validation failure.</param>
        private static T CollectUserInput<T>(string message, Func<T, bool> validate, string validationFailureMessage = null)
        {
            var input = CollectUserInput<T>(message);
            bool isValid = validate(input);
            while (!isValid)
            {
                Console.WriteLine(validationFailureMessage);
                input = CollectUserInput<T>();
                isValid = validate(input);
            }
            return input;
        }
    }
}

【讨论】:

  • 哦,是的,因为所有这些疯狂的代码都有助于我作为初学者理解 xD
【解决方案2】:

var 只是避免显式定义x 类型的语法快捷方式——编译器可以确定x 是什么类型,因为它隐含在所分配的值中。

至于你的循环,可以简化为:

var x = 0;

while (x++ < entry) {
    Console.Write("Yay!");
}

通常您会避免显式的 while(true) 循环,因为随着您的代码变得越来越复杂,它会增加循环内的退出条件永远不会满足并且您最终会陷入无限循环的风险 - 最好使用退出表达式清晰可见,而不是将其隐藏在循环内的某个位置。

【讨论】:

    【解决方案3】:

    做同样事情的惯用方法是

    for(int x = 0; x < entry;x++)
    {
       Console.Write("Yay!");
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 2019-03-08
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      相关资源
      最近更新 更多