【发布时间】:2015-01-06 17:15:21
【问题描述】:
我正在开发一个用 .NET 2.0 编写的库,它有一个返回列表类型对象的静态方法。
在单元测试期间,我遇到了一个鬼鬼祟祟的小错误,在与错误无关的行上抛出了异常。最终我发现这是这个列表返回 null 的结果。
为了防止这种情况,我看到recommended way to return这种类型的集合是使用Enumerable.Empty<TResult>。但是,这需要 Linq (.NET 3.5 +)。
在这种情况下,有没有更好的方法(最佳实践?)返回 null 以外的集合?
- 是否有
Enumerable.Empty<T>().NET 2(非 Linq)等效项?
这是我尝试使用@EagleBeak 的建议:
namespace MethodReturnEmptyCollection
{
public partial class Form1 : Form
{
private static List<ExampleItem> MyCustomList = null;
public Form1()
{
InitializeComponent();
MyCustomList = CreateEmptyListOfExampleItems();
}
private static List<ExampleItem> CreateEmptyListOfExampleItems()
{
// Throws an invalid cast exception...
return (List<ExampleItem>)GetEmptyEnumerable<List<ExampleItem>>();
}
public static IEnumerable<T> GetEmptyEnumerable<T>()
{
return new T[0];
}
}
public class ExampleItem
{
// item properties...
}
}
执行时会产生如下异常:
“System.InvalidCastException”类型的未处理异常发生在 MethodReturnEmptyCollection.exe
{"无法转换类型的对象
'System.Collections.Generic.List'1[MethodReturnEmptyCollection.ExampleItem][]' 输入 'System.Collections.Generic.List'1[MethodReturnEmptyCollection.ExampleItem]'。"}
更新:
在 EagleBeak 的输入之后,我发现这个问题很有趣:
Is it better to use Enumerable.Empty() as opposed to new List to initialize an IEnumerable?
也发现了这个:
According to Jon Skeet,您也可以使用yield break 来做同样的事情。
【问题讨论】:
标签: collections null c#-2.0 empty-list