如何验证一个空的输入

如何验证一个空的输入

问题描述:

我遇到的问题是验证输入装置,把它在一个尝试捕捉,然后通过不会传递变量,我得到这个错误:如何验证一个空的输入

使用未分配本地的变量“MainMenuSelection”

我前面,但由于某种原因,它不是现在的工作使用这种方法有效,请大家帮忙

//Take the menu selection 
try 
{ 
    mainMenuSelection = byte.Parse(Console.ReadLine()); 
} 
catch 
{ 
    Console.WriteLine("Please enter a valid selection"); 
} 


switch (mainMenuSelection) //Where error is shown 
+0

可以显示mainMenuSelection的定义吗? – BigOmega 2012-03-05 18:42:45

+1

如果没有指定异常类型,你真的不应该写'catch'。这是一个坏习惯,迟早会咬你。 – phoog 2012-03-05 18:55:12

显然,用户可以输入任何事情也不会被解析为一个byte。尝试使用Byte.TryParse()方法,它不会产生异常并返回状态标志。

你可以走得更远,如果需要用户输入,添加更多的分析:

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

看到更新,答案更新 – sll 2012-03-05 18:56:30

如果你只是关注自身的输入,你可以使用Byte.TryParse Method,然后办理假布尔情况相反。

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 
}