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

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

问题描述

我有一个具有一个最大长度要求,因为数据链接到数据库中的字串属性。 ?我应该抛出什么异常,如果主叫方试图设置字符串超过这个长度

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#代码:

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(字符串值) - 这样的情况下,的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.

这问题很可能也将扩大到包括各类财产setter方法​​进行数据验证的,但我在上述情况下特别感兴趣。

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.

推荐答案

有通过与反射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
    }
}

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

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