Determine if object derives from collection type

前端 未结 11 2235
时光说笑
时光说笑 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:43

    In order to get the actual type of T at runtime, you can use the typeof(T) expression. From there the normal type comparison operators will do the trick

    bool isEnumerable = typeof(IEnumerable).IsAssignableFrom(typeof(T));
    

    Full Code Sample:

    static bool Foo()
    {
      return typeof(IEnumerable).IsAssignableFrom(typeof(T));
    }
    
    Foo>();  // true
    Foo(); // false
    

提交回复
热议问题