If object is Generic List

前端 未结 6 459
既然无缘
既然无缘 2021-01-11 10:32

Is there any way to determine if an object is a generic list? I\'m not going to know the type of the list, I just know it\'s a list. How can I determine that?

6条回答
  •  青春惊慌失措
    2021-01-11 10:41

    The question is ambiguous.

    The answer depends on what you mean by a generic list.

    • A List ?

    • A class that derives from List ?

    • A class that implements IList (in which case an array can be considered to be a generic list - e.g. int[] implements IList)?

    • A class that is generic and implements IEnumerable (this is the test proposed in the accepted answer)? But this will also consider the following rather pathological class to be a generic list:

    .

    public class MyClass : IEnumerable
    {
        IEnumerator IEnumerable.GetEnumerator()
        {
            return null;
        }
    }
    

    The best solution (e.g. whether to use GetType, IsAssignableFrom, etc) will depend on what you mean.

提交回复
热议问题