微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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!");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐