【发布时间】:2019-11-25 23:18:22
【问题描述】:
这是我昨天遇到的。我想知道这里的最佳做法是什么。我可以像这样创建此类的一个实例,或者来自其他地方的参数可以为空:
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 似乎有点尴尬。
【问题讨论】:
-
这是一个时尚感的问题,取决于你写这篇文章的水平,也涉及到常识。如果它是
null的特殊情况,那么你抛出一个ArgumentNullException。用户是否期望它在这里是null?忽略此null是否有任何重大影响?低级 api 被大量验证,因为它们经过大量测试并且需要一致的结果,高级混合在一起的代码往往有更多的余地。但是还是回到了原点,是不是很特别? -
我同意上述观点,这取决于 ItemsSource 具有值的重要性。你可以简单地做: if( items == null ) return;或 if( items == null ) this.ItemsSource = new List
()。这将允许您继续执行。
标签: c# collections notnull