3

我有以下课程:

class Foo
{
    public Foo()
        : this(new List<Bar>())
    {
    }

    public Foo(IEnumerable<Bar> bars)
    {
        Bars = bars;
    }

    public IEnumerable<Bar> Bars { get; set; }

    public Bar GetSingleBar(Data data)
    {
        // this method returns a single Bar from the Bars property above
        // this method returns the Bar which matches the data parameter
        // this method should not return null
        // this method throws a NoBarsFoundException if
        //   (a) Bars is empty or
        //   (b) no bar in Bars matches the data
    }
}

Bars如果是我该怎么办null?我应该在 setter 中Bars抛出异常还是应该在 中抛出异常GetSingleBar?(该方法GetSingleBar是唯一使用该Bars属性的方法。)

我应该扔一个ArgumentException, ArgumentNullException, InvalidOperationException, 还是NoBarsFoundException?

4

6 回答 6

5

大概:System.ArgumentNullException

Nothing将空引用(在 Visual Basic 中)传递给不接受它作为有效参数的方法时引发的异常。

throw new ArgumentNullException("bars");
于 2012-06-22T13:26:17.307 回答
2

I'd say when Bars is null and it should never be null, then you should throw an InvalidOperationException, since the operation GetSingleBar is invalid in the object's current state, and Bars is a property of your class.

ArgumentNullException, as the name says, should be thrown only when an argument is null.

I would consider making Bars readonly though (if possible).

于 2012-06-22T13:28:12.593 回答
0

This is probably a good reason for not using a property setter, but instead a method, based on an answer from this question:

Best practices: throwing exceptions from properties

This is because the property will become potentially unsafe in the form of the exception.

in lieu of bothering with that, ArgumentNullException is the standard when the supplied argument is null (for methods at least).

If you then try to use Bars before it is set or something, then I would throw an InvalidOperationException to signify that the object isn't in a valid state to cater for the action.

于 2012-06-22T13:28:08.880 回答
0

我会在 GetSingleBar 方法中抛出 NoBarsFoundException。这样,您可以有另一个方法允许 GetSingleBar 为空。

如果您总是想防止 Bars 为 Null,也许您应该在构造函数中设置它并使其私有?

于 2012-06-22T13:29:10.790 回答
0

如果一个空集合导致一个对象不一致,我会抛出 setter。

Bars您永远不知道将来会使用哪些其他新方法。

于 2012-06-22T13:31:41.707 回答
0

您应该在设置值时抛出错误,因为那是发生“错误”的地方。

ArgumentNullException 也是正确的错误消息。

我遇到的一个问题是你应该有一个 set 方法和一个只读属性,因为大多数程序员不希望抛出异常。这是完全可以接受的——属性和异常

于 2012-06-22T13:31:50.357 回答