如果属性为null,哪个/什么时候抛出异常?

cm0*_*007 3 c# exception-handling exception

我有以下课程:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我应该抛出ArgumentException,ArgumentNullException,InvalidOperationException,或NoBarsFoundException

I a*_*ica 5

可能:System.ArgumentNullException

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

throw new ArgumentNullException("bars");
Run Code Online (Sandbox Code Playgroud)