Jos*_*eph 3 c# validation exception try-catch
我如何尝试捕获内部Letter调用try catch Program?目前我使用bool作为验证器,但我想要任何假bool抛出错误并Program看到这个.
这样做的最佳方法是什么,因为目前Program无法判断属性是否设置错误.
Program.cs
Letter a = new Letter();
try
{
a.StoredChar = '2';
}
catch (Exception)
{
a.StoredChar = 'a';
}
// I want this to print 'a' because the '2' should throw a catch somehow
// I don't know how to set this up.
Console.WriteLine(a.StoredChar);
Run Code Online (Sandbox Code Playgroud)
Letter.cs
class Letter
{
char storedChar;
public char StoredChar
{
set { validateInput(value);}
get { return storedChar;}
}
bool validateInput(char x)
{
if ( ( (int)x >= 65 && (int)x <= 90 ) || ( (int)x >= 97 && (int)x <= 122 ) )
{
storedChar = x;
return true;
}
else
{
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
只需在Letter类中抛出异常.像这样的Smth:
private void validateInput(char x)
{
if ( ( (int)x >= 65 && (int)x <= 90 ) || ( (int)x >= 97 && (int)x <= 122 ) )
{
storedChar = x;
}
else
{
throw new OutOfRangeException("Incorrect letter!");
}
}
Run Code Online (Sandbox Code Playgroud)