简体   繁体   English

如何从IList <>获取项目数作为对象?

[英]How to get the items count from an IList<> got as an object?

In a method, I get an object . 在一个方法中,我得到一个object

In some situation, this object can be an IList of "something" (I have no control over this "something"). 在某些情况下,这个object可能是一个“某事”的IList (我无法控制这个“某事”)。

I am trying to: 我在尝试着:

  1. Identify that this object is an IList (of something) 确定此对象是IList (某事物)
  2. Cast the object into an " IList<something> " to be able to get the Count from it. object转换为“ IList<something> ”以便能够从中获取Count

For now, I am stuck and looking for ideas. 现在,我陷入困境并寻找想法。

You can check if your object implements IList using is . 您可以检查您的object是否使用is实现IList

Then you can cast your object to IList to get the count. 然后,您可以将objectIList以获取计数。

object myObject = new List<string>();

// check if myObject implements IList
if (myObject  is IList)
{
   int listCount = ((IList)myObject).Count;
}
if (obj is ICollection)
{
    var count = ((ICollection)obj).Count;
}
        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。

Since all you want is the count, you can use the fact that anything that implements IList<T> also implements IEnumerable ; 因为你想要的只是计数,你可以使用任何实现IList<T>也实现IEnumerable ; and furthermore there is an extension method in System.Linq.Enumerable that returns the count of any (generic) sequence: 此外, System.Linq.Enumerable中有一个扩展方法,它返回任何(通用)序列的计数:

var ienumerable = inputObject as IEnumerable;
if (ienumerable != null)
{
    var count = ienumerable.Cast<object>().Count();
}

The call to Cast is because out of the box there isn't a Count on non-generic IEnumerable . Cast的调用是因为开箱即用的非通用IEnumerable没有Count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM