C# 如何从作为对象的 IList<> 获取项目计数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9000322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the items count from an IList<> got as an object?
提问by remio
In a method, I get an object.
在一个方法中,我得到一个object.
In some situation, this objectcan be an IListof "something" (I have no control over this "something").
在某些情况下,这object可能是IList“某事”(我无法控制这个“某事”)。
I am trying to:
我在尝试着:
- Identify that this object is an
IList(of something) - Cast the
objectinto an "IList<something>" to be able to get theCountfrom it.
- 确定这个对象是
IList(某物的) - 将 the
object转换为 "IList<something>" 以便能够从中获取Count。
For now, I am stuck and looking for ideas.
现在,我被困在寻找想法。
采纳答案by dknaack
You can check if your objectimplements IListusing is.
你可以,如果你的检查object工具IList使用is。
Then you can cast your objectto IListto get the count.
然后你可以投射你的objecttoIList来计算。
object myObject = new List<string>();
// check if myObject implements IList
if (myObject is IList)
{
int listCount = ((IList)myObject).Count;
}
回答by Danny Varod
if (obj is ICollection)
{
var count = ((ICollection)obj).Count;
}
回答by Petar Ivanov
object o = new int[] { 1, 2, 3 };
//...
if (o is IList)
{
IList l = o as IList;
Console.WriteLine(l.Count);
}
This prints 3, because int[] is a IList.
这将打印 3,因为 int[] 是一个 IList。
回答by AakashM
Since all you want is the count, you can use the fact that anything that implements IList<T>also implements IEnumerable; and furthermore there is an extension method in System.Linq.Enumerablethat returns the count of any (generic) sequence:
由于您想要的只是计数,因此您可以使用任何实现的事实IList<T>也实现IEnumerable; 此外,还有一个扩展方法System.Linq.Enumerable可以返回任何(通用)序列的计数:
var ienumerable = inputObject as IEnumerable;
if (ienumerable != null)
{
var count = ienumerable.Cast<object>().Count();
}
The call to Castis because out of the box there isn't a Counton non-generic IEnumerable.
调用 toCast是因为开箱即用,没有Counton non-genericIEnumerable。

