c# - c#扩展方法Array.Empty .net 4.5
问题描述
我实现Array.Empty<T>
是因为想使用这段代码
foreach (Control c in controls.OrEmptyIfNull())
{
this.Controls.Add(c);
}
但我的程序使用的是 .NET 4.5 版,我不想更改。
所以在下面编码
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;
注意:考虑到迁移到可空类型,我会对这些扩展方法中的任何一个持怀疑态度。但是,由于您被困在 2012 年,因此可能没有什么危害 :)
推荐阅读
- javascript - 展平嵌套数组
- swagger-ui - 使用格式为 ***-service 的服务名称打开 Api swagger 文档
- python - 如何对列表中的字符串进行分类,因为它包含确定的字符,python
- javascript - Number(i) 在下面的代码中被传递到函数中。有人可以解释循环在代码中是如何工作的
- javascript - 获取静态函数以返回异步值
- python - 尽管配置,Django 日志配置被忽略
- c# - 在群聊中搜索消息扩展问题
- java - 如何将推断的三元组输入(其他)SHACL 规则?
- compiler-construction - yy 在扫描仪/词法分析器(如 jflex)中的意义
- javascript - Zingchart 通过 java 调用 getimagedata api