C# 如何验证空输入
我遇到的问题是验证输入意味着将其放入一个try-catch中,这样就无法传递变量,我得到了以下错误: 使用未分配的局部变量“MainMenuSelection” 我以前验证过使用此方法,但由于某些原因,它现在不起作用,请帮助C# 如何验证空输入,c#,validation,C#,Validation,我遇到的问题是验证输入意味着将其放入一个try-catch中,这样就无法传递变量,我得到了以下错误: 使用未分配的局部变量“MainMenuSelection” 我以前验证过使用此方法,但由于某些原因,它现在不起作用,请帮助 //Take the menu selection try { mainMenuSelection = byte.Parse(Console.ReadLine()); } catch { Console.WriteLine("Please enter a v
//Take the menu selection
try
{
mainMenuSelection = byte.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a valid selection");
}
switch (mainMenuSelection) //Where error is shown
显然,用户可以输入任何不会被解析为单个
字节的内容。尝试使用不生成异常且只返回状态标志的方法
如果需要,您可以进一步为用户输入添加更多分析:
// Initialize by a default value to avoid
// "Use of unassigned local variable 'MainMenuSelection'" error
byte mainMenuSelection = 0x00;
string input = Console.ReadLine();
// If acceptable - remove possible spaces at the start and the end of a string
input = input.Trim();
if (input.Lenght > 1)
{
// can you do anything if user entered multiple characters?
}
else
{
if (!byte.TryParse(input, out mainMenuSelection))
{
// parsing error
}
else
{
// ok, do switch
}
}
也许你只需要一个字符而不是一个字节?
那么就做:
// Character with code 0x00 would be a default value.
// and indicate that nothing was read/parsed
string input = Console.ReadLine();
char mainMenuSelection = input.Length > 0 ? input[0] : 0x00;
如果您只关心输入本身,那么可以使用,然后处理假布尔值
byte mainMenuSelection;
if (Byte.TryParse(Console.ReadLine(), out mainMenuSelection)
{
switch(mainMenuSelection);
}
else
{
Console.WriteLine("Please enter a valid selection");
}
更好的方法是使用byte.TryParse()
。它是专门为这些类型的场景设计的
byte b;
if (byte.TryParse("1", out b))
{
//do something with b
}
else
{
//can't be parsed
}
您可以显示mainMenuSelection的定义吗?您确实不应该在未指定异常类型的情况下编写catch
。这是一个迟早会咬你的坏习惯。