我实现了Array.Empty<T>
,因为我想使用这个代码
foreach (Control c in controls.OrEmptyIfNull())
{
this.Controls.Add(c);
}
OrEmptyIfNull扩展方法
但是我的程序使用的是.NET 4.5版本,我不想更改。
Array.Emtpy
因此编码在之下
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列表为空之前进行检查更漂亮的
由于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;
注意:考虑到移动到可为null的类型,我对这些扩展方法中的任何一种都持怀疑态度。然而,由于你被困在2012年,可能没有什么害处:(
您已经定义了EmptyArray<T>
,为什么不直接使用它呢?
return source ?? EmptyArray<T>.Value;