如何在从字符串解析的int中捕获错误?

use*_*127 1 c#

我正在寻找一种有效的方法,并有助于捕获错误输入.如果输入不是1或2,我需要处理.或者 - 或者只是任何一封信.我试过捕获,似乎没有什么工作:/

有人想让我尝试一下吗?我很满意任何建议!! Thx提前!

问候

我到目前为止编写的代码如下所示:

console.WriteLine();
Console.Write("Make your choice: ");


int myinput = int.Parse(Console.ReadLine());

if (myinput == 1)
{
FirstEvent();
}
if (myinput == 2)
{
SecondEvent();
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

通常我们使用TryParse方法

int myinput = 0;
if(false == int.TryParse(Console.ReadLine(), out myInput))
   // Error, not an integer
   Console.WriteLine("Please input 1 or 2");
else
{
    if (myinput == 1) 
    { 
        FirstEvent(); 
    } 
    else if (myinput == 2) 
    { 
        SecondEvent(); 
    } 
    else
        Console.WriteLine("Please input 1 or 2");
}
Run Code Online (Sandbox Code Playgroud)