从属性设置器抛出什么异常? [英] What exception to throw from a property setter?

查看:19
本文介绍了从属性设置器抛出什么异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有最大长度要求的字符串属性,因为数据链接到数据库.如果调用者尝试设置超过此长度的字符串,我应该抛出什么异常?

I have a string property that has a maximum length requirement because the data is linked to a database. What exception should I throw if the caller tries to set a string exceeding this length?

例如这个 C# 代码:

For example, this C# code:

public string MyProperty
{
    get
    {
        return _MyBackingField;
    }
    set
    {
        if (value.Length > 100)
            throw new FooException("MyProperty has a maximum length of 100.");

        _MyBackingField = value;
    }
}

我考虑过ArgumentException,但似乎不太对.技术上,它是一个函数 - MyProperty_set(string value) - 所以 ArgumentException 的情况是可以的,但它不被称为消费者眼中的功能 - 它位于赋值运算符的右侧.

I considered ArgumentException, but it just doesn't seem right. Technically, it is a function - MyProperty_set(string value) - so a case for ArgumentException can be made, but it's not being called as a function to the consumer's eyes - it's on the right side of an assignment operator.

这个问题可能也可以扩展到包括在属性设置器中完成的各种数据验证,但我对上述案例特别感兴趣.

This question could probably also be extended to include all kinds of data validation done in property setters, but I'm particularly interested in the above case.

推荐答案

用 Reflector 看看 mscorlib.dll,在类似 System.String.StringBuilder.Capacity 的情况下微软使用 ArgumentOutOfRangeException() 类似:

Have a look through mscorlib.dll with Reflector, in a similar situation such as System.String.StringBuilder.Capacity Microsoft use ArgumentOutOfRangeException() similar to:

public int PropertyA
{
    get
    {
        return //etc...
    }
    set
    {
        if (condition == true)
        {
            throw new ArgumentOutOfRangeException("value", "/* etc... */");
        }
        // ... etc
    }
}

这篇关于从属性设置器抛出什么异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆