寻求C#代码简化方法,恳请技术人员协助答疑
Hey there! Since you're new to coding and looking to simplify your C# code, let's break this down—we'll not only make it cleaner but also more robust (so it doesn't crash if someone enters something weird).
First, here's your original code for reference:
static void Main(string[] args) { Console.Write("How many tests would you like to do? 1 to 10: "); int tests = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(); }
Simplified + Robust Version
This version keeps things concise while handling invalid input (like letters or numbers outside 1-10), which is super helpful for new developers:
static void Main(string[] args) { Console.Write("How many tests would you like to do? 1 to 10: "); // Safely parse input and validate range in one loop while (!int.TryParse(Console.ReadLine(), out int tests) || tests is < 1 or > 10) { Console.Write("Invalid input! Please enter a number between 1 and 10: "); } Console.WriteLine(); }
What we changed (and why):
- Replaced
Convert.ToInt32withint.TryParse: This method checks if the input is a valid integer without crashing the program. If the input is bad, it just returnsfalse. - Combined validation into a
whileloop: Instead of writing separate checks for "is this a number?" and "is it in range?", we do both in one loop. The loop keeps running until the user enters a valid value. - Inlined variable declaration: We declare
int testsdirectly inside theTryParsecall without int tests, so we don't need a separate line to declare the variable first.
If you really want the absolute shortest version (though it doesn't handle bad input, so it's riskier), you could do this:
static void Main(string[] args) { Console.Write("How many tests would you like to do? 1 to 10: "); int tests = int.Parse(Console.ReadLine()); Console.WriteLine(); }
But I strongly recommend the first version—it's just as clean, way more user-friendly, and teaches good habits for handling input early on.
内容的提问来源于stack exchange,提问作者user9769984

