c# – 如何使用Try和Catch设置值

我如何能够在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!");
    }
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...