也许这对你来说有点高级,但如果你心情愉快,你可以定义一个处理用户输入解析的类。这样您就可以将该逻辑与您的主程序分开(请参阅separation of concerns)。
public class UserEntry
{
private readonly string _originalValue;
public UserEntry(string input)
{
_originalValue = input;
}
public bool IsInt
{
get
{
return int.TryParse(_originalValue, out var dummy);
}
}
public int ToInt()
{
return ToInt(default(int));
}
public int ToInt(int defaultValue)
{
int result;
bool ok = int.TryParse(_originalValue, out result);
return ok ? result : defaultValue;
}
public override string ToString()
{
return _originalValue;
}
static public implicit operator UserEntry(string input)
{
return new UserEntry(input);
}
static public implicit operator Int32(UserEntry input)
{
return input.ToInt();
}
}
如果我们使用隐式转换运算符,它会使事情变得非常简单。例如,所有这些现在都是合法的:
UserEntry entry = Console.ReadLine();
if (!entry.IsInt) continue;
if (entry < 10) return entry;
如果我们将此应用于您的示例,它会缩短您的代码一点,并且可以说也使其更清晰。
public class Program
{
private const int MaximumOrder = 10;
public static void Main()
{
var n = AskForNumberOfShirts();
Console.WriteLine("OK, I'll order {0} shirts.", n);
}
public static int AskForNumberOfShirts()
{
while (true)
{
Console.WriteLine("Enter the number of shirts to order:");
UserEntry entry = Console.ReadLine();
if (!entry.IsInt)
{
Console.WriteLine("You entered an invalid number.");
continue;
}
if (entry > MaximumOrder)
{
Console.WriteLine("{0} is too many! Please enter {1} or fewer.", entry, MaximumOrder);
continue;
}
return entry;
}
}
}
注意事项:
- 我怀疑你可以订购半件衬衫,所以我使用
int 而不是double 来存储衬衫的数量。
- 我重构了逻辑分支以使用机会回报,a.ka.守卫模式。 See this article for why I do this。
- 我将常量值
10 提取为它自己的符号MaximumOrder。这应该会让你在作业上加分。
输出:
Enter the number of shirts to order:
22
22 is too many! Please enter 10 or fewer.
Enter the number of shirts to order:
sdlfkj
You entered an invalid number.
Enter the number of shirts to order:
9
OK, I'll order 9 shirts.
Working example on DotNetFiddle