【问题标题】:C# 2.0 Empty CollectionC# 2.0 空集合
【发布时间】: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


    【解决方案1】:

    只需扔掉两个私有方法并在构造函数中初始化您的列表,如下所示:

    MyCustomList = new List&lt;ExampleItem&gt;();

    PS:Enumerable.Empty&lt;T&gt; 无论如何都不适合你。 List&lt;T&gt; 实现 IEnumerable&lt;T&gt;,而不是相反。

    【讨论】:

    • 能否请您发布一些代码?我发布的方法适用于 .Net 2.0。
    • 哦,现在我明白了,解决方案甚至应该简单得多。我不知道您有一个 List 类型的私有字段。您不能将数组转换为列表。
    • 哇,太明显了,我什至没有考虑。那么,Enumerable.Empty&lt;TResult&gt; 的目的是什么?似乎它的所有好处都是提高可读性并使事情更通用。
    • 如果您的字段是 IEnumerable 类型,Enumerable.Empty 实际上会起作用。因为您的字段属于 List 类型,您只能分配从 List 继承的类的实例。
    猜你喜欢
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    • 2010-09-16
    相关资源
    最近更新 更多