2017-08-24 49 views
1
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循环所代表的是什么。此代码示例来自树屋挑战,但'var x'如何使程序按预期工作?感谢您的帮助! :)C# - 最后一个while循环和'var x'是做什么的?

+0

它会循环打印'yay'的进入时间。 for循环会更清晰 – pm100

+1

使用调试器来遍历代码,您将看到它的具体功能。 –

+1

x是一个计数器,在'Yay'的每个打印输出后递增。在x = entry之后,while循环中的逻辑将强制它退出(break)。如果您发现while循环逻辑有点复杂,您可以使用简单的for循环。 –

回答

0

var只是一个语法快捷方式,用于避免明确定义x的类型 - 编译器可以确定x是什么类型,因为它在被分配的值中是隐含的。

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

var x = 0; 

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

通常你会避免一个明确的while(true)循环因为你的代码变得更为复杂,它引发的风险循环内的退出条件从来没有见过面,最终会产生一个无限循环 - 最好让退出表达清晰可见,而不是隐藏在循环内的某个位置。

0

惯用的方式做同样的事情是

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

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; 
     } 
    } 
} 
+0

哦,是的,所有这些疯狂的屁股代码帮助我理解为一个初学者xD –