代码之家  ›  专栏  ›  技术社区  ›  Neil Barnwell

如何判断类型是列表、数组还是IEnumerable或

  •  32
  • Neil Barnwell  · 技术社区  · 14 年前

    最简单的方法是什么 Type

    3 回复  |  直到 14 年前
        1
  •  55
  •   SLaks    14 年前

    支票 typeof(IEnumerable).IsAssignableFrom(type)

    每个集合类型,包括数组和 IEnumerable<T> ,工具 IEnumerable .

        2
  •  0
  •   Ala Musleh    9 年前
    if (objType.IsArray || objType.IsGenericType)
    {
    
    }
    
        3
  •  0
  •   Raj Kumar - rajkrs    5 年前
    typeof(IEnumerable<object>).IsAssignableFrom(propertyInfo.PropertyType)
    

    如果我们是从普通的T。

        4
  •  -1
  •   SandRock Jerry Birchler    5 年前

    这并不能完全回答这个问题,但我认为这是一个有用的代码谁登陆了这篇文章。

    给予 或者 ,您可以使用以下代码 检查对象是否为数组

    IList<string> someIds = new string[0];
    if (someIds is Array)
    {
        // yes!
    }
    
    IList<string> someIds = new List<string>(0);
    if (someIds is Array)
    {
        // nop!
    }
    

    不同的是我们没有和任何 Type 对象,但在 物体。

        5
  •  -7
  •   bleepzter    14 年前

    很简单。最简单的事情是:

    IList<T> listTest = null;
    
    try{
         listTest = ((IList<T>)yourObject);
    }
    catch(Exception listException)
    {
        //your object doesn't support IList and is not of type List<T>
    }
    
    IEnumerable<T> enumerableTest = null;
    
    try{
         enumerableTest = ((IEnumerable<T>)yourObject);
    }
    catch(Exception enumerableException)
    {
         //your object doesn't suport IEnumerable<T>;
    }
    

    您也可以尝试不涉及多个try/catch块的方法。最好能避免使用这些条件,因为每个条件实际上都是由运行时在运行时计算的。。。这是一个糟糕的代码(尽管有时没有办法解决)。

    Type t = yourObject.GetType();
    
    if( t is typeof(List<OjbectType>) )   //object type is string, decimal, whatever...
    {
         // t is of type List<ObjectType>...
    }
    else if( t is typeof(IEnumerable<ObjectType>)
    {
         // t is of type IEnumerable<ObjectType>...
    }
    else
    {
        // t is some other type.
        // use reflection to find it.
    }