c# – 如何使用Try和Catch设置值
发布时间:2020-12-16 00:07:51 所属栏目:百科 来源:网络整理
导读:我如何能够在Letter中尝试捕获一个程序中的try catch?目前我使用bool作为验证器,但我想要任何假bool抛出错误,并且程序看到这个. 什么是最好的方法,因为目前程序无法判断属性是否设置错误. Program.cs中 Letter a = new Letter(); try { a.StoredChar = '2';
我如何能够在Letter中尝试捕获一个程序中的try catch?目前我使用bool作为验证器,但我想要任何假bool抛出错误,并且程序看到这个.
什么是最好的方法,因为目前程序无法判断属性是否设置错误. 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); 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; } } } 解决方法
只需在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!"); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |