首页 > 解决方案 > 允许 IList 参数为空或如果为空则抛出异常是否有意义?

问题描述

这是我昨天遇到的。我想知道这里的最佳做法是什么。我可以像这样创建此类的一个实例,或者参数可以是来自其他地方的 null:

CustomItemsSourceDialogViewModel itemsSource = new CustomItemsSourceDialogViewModel();
itemsSource.Initialize(null); // I get nullReferenceException

这是提到的类定义:

public class CustomItemsSourceDialogViewModel
{
  public void Initialize(IList<string> items)
  {
    // it doesn't make sense to allow parameter items to be null
    // it only makes sense to allow not null items collection
    // so we can operate on it.
    // if items is null we get system.nullReferenceException
    if (items.Count > 0)
      // aggregate is a system.linq static method
      this.ItemsSource = items.Aggregate((x, y) => x + "\r\n" + y);
  }
}

我更喜欢让我的收藏/列表不为空。换句话说,集合应该有一个空集合的默认值。这样开发人员或用户就不会得到那个讨厌的 NullReferenceException。

关于方法的列表参数,我是否应该在参数为空时抛出异常并通知用户:

public void Initialize(IList<string> items)
{
  if( items == null )
    throw new Exception("Parameter items is null. It should be a valid list.");
  ...

另一种解决方案是检查它是否不为空:

public void Initialize(IList<string> items)
{
  if (items != null && items.Count > 0)
    this.ItemsSource = items.Aggregate((x, y) => x + "\r\n" + y);
 }

但是总是检查 if not null 似乎有点尴尬。

标签: c#collectionsnotnull

解决方案


为了添加 TheGeneral 和 Will 所写的内容 - 您永远不想看到NullReferenceException生产代码。

您需要做的是确定是否需要将 nullIList传递给此方法,更重要的是,您是否可以处理此类情况是一种不会破坏业务逻辑的方法。
如果这两个问题的答案都是“否”,那么您应该抛出ArgumentNullException - 因为此异常以最精确的方式传达了问题 - 该方法期望参数不为空:

public void Initialize(IList<string> items)
{
    if( items is null ) // requires c# 7 or higher
    { 
        throw new ArgumentNullException(nameof(items));
    }

    // rest of the code here
}

但是,如果您的业务逻辑可以在没有它的情况下继续进行IList,并且null预计将 a 发送到此方法,那么您应该在方法内部处理这种情况,而不是抛出异常 -异常是针对特殊情况的 - 所以如果 nullIList有与空的效果相同IList,预计将传递给方法 - 它不能被视为异常,因此不应触发抛出异常。

public void Initialize(IList<string> items)
{
    // just a shorter way for the same condition - requires c# 6 or higher
    if (items?.Any() ?? false)
    {
        this.ItemsSource = Items.Aggregate((x, y) => x + "\r\n" + y);
    } // I like to always use code blocks for conditions etc'. I find it more readable.
}

推荐阅读