首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >阵列的IsNullOrEmpty等价物?C#

阵列的IsNullOrEmpty等价物?C#
EN

Stack Overflow用户
提问于 2011-12-19 18:40:07
回答 8查看 92.8K关注 0票数 48

在.NET库中是否有一个函数可以返回true或false来判断数组是空的还是空的?(类似于string.IsNullOrEmpty)。

我在Array类中查找了类似这样的函数,但什么也看不到。

代码语言:javascript
复制
var a = new string[]{};
string[] b = null;
var c = new string[]{"hello"};

IsNullOrEmpty(a); //returns true
IsNullOrEmpty(b); //returns true
IsNullOrEmpty(c); //returns false
EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2011-12-19 18:43:05

没有现有的扩展方法,但您可以使用此扩展方法:

代码语言:javascript
复制
/// <summary>Indicates whether the specified array is null or has a length of zero.</summary>
/// <param name="array">The array to test.</param>
/// <returns>true if the array parameter is null or has a length of zero; otherwise, false.</returns>
public static bool IsNullOrEmpty(this Array array)
{
    return (array == null || array.Length == 0);
}

只需将其放在某个扩展类中,它就会扩展Array,使其具有IsNullOrEmpty方法。

票数 66
EN

Stack Overflow用户

发布于 2011-12-19 18:43:50

您可以创建自己的扩展方法:

代码语言:javascript
复制
public static bool IsNullOrEmpty<T>(this T[] array)
{
    return array == null || array.Length == 0;
}
票数 35
EN

Stack Overflow用户

发布于 2014-03-14 21:12:51

如果使用ICollection<T>,则更加通用

代码语言:javascript
复制
public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
{
    return collection == null || collection.Count == 0;
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8560106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档