首页 > 解决方案 > c#扩展方法Array.Empty .net 4.5

问题描述

我实现Array.Empty<T>是因为想使用这段代码

foreach (Control c in controls.OrEmptyIfNull())
{
    this.Controls.Add(c);
}

OrEmptyIfNull 扩展方法

但我的程序使用的是 .NET 4.5 版,我不想更改。

数组.Emppy

所以在下面编码

public static class ExtensionClass
{
    public static T[] Empty<T>(this Array array)
    {
        return EmptyArray<T>.Value;
    }

    public static IList<T> OrEmptyIfNull<T>(this IList<T> source)
    {
        return source ?? Array.Empty<T>();
    }

    internal static class EmptyArray<T>
    {
        public static readonly T[] Value = new T[0];
    }
}

但是这一行发生了错误return source ?? Array.Empty<T>();

错误 CS0117“数组”不包含“空”的定义

Array.Empty()在 foreach 列表为空之前如何使用或检查更漂亮

标签: c#

解决方案


由于Array.Empty<T>仅可从.Net 4.6 + 获得,因此您可以轻松地新建一个List<T>new T[0];两者都实现IList<T>

return source ?? new List<T>();

// or

return source ?? new T[0];

还值得注意的是,源代码Array.Empty<T>基本上只是引用静态类型以获得最小分配,因此您可以相当容易地复制此功能:

internal static class EmptyArray<T>
{
    public static readonly T[] Value = new T[0];
}

...

return source ?? EmptyArray<T>.Value;

注意:考虑到迁移到可空类型,我会对这些扩展方法中的任何一个持怀疑态度。但是,由于您被困在 2012 年,因此可能没有什么危害 :)


推荐阅读