我想编写一个方法来判断ICollection实例是否存在NullOrEmpty,例如:
public static bool IsCollectionNullOrEmpty<T>(ICollection<T> instance)
{
if (instance == null)
{
return true;
}
else
{
if (instance.GetType() == typeof(Array))
{
return new List<T>(instance).Count <= 0;
}
else
{
return instance.Count <= 0;
}
}
}
实际上,我不知道如何获得实例的类型,如果是喜欢T [],请帮助我,如果有一个例子将是伟大的,谢谢
答案 0 :(得分:3)
你可能使用GetType().IsArray
,但这限制了您对纯数组类型的限制。更通用的解决方案是检查它的Count
属性,因为您已经知道它是ICollection<T>
。这也适用于数组。
答案 1 :(得分:2)
不确定为什么你需要这样奇怪的演员,因为数组已经实现了ICollection<T>
:
public static bool IsCollectionNullOrEmpty<T>(this ICollection<T> instance)
{
return instance == null ? true : instance.Count == 0;
}
添加了this
以允许调用扩展方法:
var isEmpty = (new int[0]).IsCollectionNullOrEmpty();
答案 2 :(得分:0)
您可以使用:
if(instance.GetType() == typeof (T[]))
答案 3 :(得分:0)
更好的方法是接受一个IEnumerable(比ICollection更通用,因为ICollection实现IEnumerable)并简单地检查它为null,否则从linq的运算符返回Any()
public static bool IsCollectionNullOrEmpty<T>(IEnumerable<T> instance)
{
if (instance == null)
{
return true;
}
return !instance.Any();
}
或者正如其他人提到的那样,如果你想坚持ICollection那么就没有必要检查数组和所有这些,你接受ICollection,而ICollection有一个count成员,所以你可以直接使用count,不需要传递数组到一个新的列表构造函数来访问一个count属性。
你不能在随机数组上执行.Count的原因是因为实现是隐藏的但是因为在这个上下文中你的参数不是explcitely一个数组而是一个ICollection你可以只调用.Count就可以了(数组有一个.Count方法,它只是隐藏但它必须拥有它,因为它实现了ICollection)
https://msdn.microsoft.com/en-us/library/ms173157.aspx
这就是原因:
((ICollection)(new int[] { 0 })).Count; // this compiles
(new int[] { 0 }).Count; // this doesn't, althought it's the same object
所以如果你真的想像你一样写它,你可以简化它:
public static bool IsCollectionNullOrEmpty<T>(ICollection<T> instance)
{
if (instance == null)
{
return true;
}
return instance.Count <= 0; // this does the exact same thing as your previous else block except it's massively simpler and doesn't create a new list
}
请注意,这听起来根本不像一个有用的方法(我会亲自删除它),因为它几乎不会在Any运算符上添加任何值,所以我只需要检查null是否需要然后调用any为此创建一个自定义方法。
我每次有一个我需要检查的集合,而不是使用这种方法,我只是做以下事情:
if(mycollection == null || (!mycollection.Any())