Determine if object derives from collection type

前端 未结 11 2060
时光说笑
时光说笑 2021-02-05 04:53

I want to determine if a generic object type (\"T\") method type parameter is a collection type. I would typically be sending T through as a Generic.List but it could be any co

11条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 05:51

    I came across the same issue while attempting to serialize any object to JSON format. Here is what I ended up using:

    Type typ = value.GetType();
    
    // Check for array type
    if(typeof(IEnumerable).IsAssignableFrom(typ) || typeof(IEnumerable<>).IsAssignableFrom(typ))
    { 
        List list = ((IEnumerable)value).Cast().ToList();
        //Serialize as an array with each item in the list...
    }
    else
    {
        //Serialize as object or value type...
    }
    
        

    提交回复
    热议问题