我試圖創建if語句或try/catch,希望在控制檯應用程序接收到輸入的條件下執行(即我轉換爲Int32)不是一個整數。這是我一直在使用的代碼片段:根據輸入是否是字符串/ int執行if語句或try/catch
Console.WriteLine("What year was your car made? [MUST BE IN YEAR FORMAT]");
caryearchk = Console.ReadLine();
if (caryearchk.GetType() != int) // Can't figure out a way to return a bool through .GetType()
{
Console.Write("Error. you MUST submit this in an integer form. The application will now close.");
Console.ReadLine();
}
else
{
}
caryear = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("What is the drivetrain? [ FWD /// RWD /// AWD /// 4WD ]");
cartrain = Console.ReadLine();
}
Car car = new Car(carmake,
如果有任何其他/更有效的方法來解決這個問題,我寧願更喜歡那個。我渴望知道許多不同的方法來解決這樣的基本問題
如果Console.ReadLine();返回一個字符串,如「兩千一十五」不會導致應用程序以.TryParse()結束?我的目標是,如果用戶輸入某種錯誤的格式或無意中添加了一個字母,就可以拋出錯誤 –