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;
}
}
}
它会循环打印'yay'的进入时间。 for循环会更清晰 – pm100
使用调试器来遍历代码,您将看到它的具体功能。 –
x是一个计数器,在'Yay'的每个打印输出后递增。在x = entry之后,while循环中的逻辑将强制它退出(break)。如果您发现while循环逻辑有点复杂,您可以使用简单的for循环。 –