Determine if object derives from collection type

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

    While I can't be certain what the original poster's intent was, there have been several responses to the effect of casting to IEnumerable for testing. That's fine, but everyone should be aware that string instances pass this test, which may not be something the original author intended. I know I certainly didn't when I went looking for an answer and found this post:

    string testString = "Test";
    Console.WriteLine(testString as IEnumerable != null);  // returns true
    

    I am in the process of trying to write a custom serializer that uses reflection to accomplish certain tasks. As part of a task, I need to determine if a property value is a collection/array/list of items or a single property value. What is particularly annoying is that several Linq expressions actually result in an enumerable type value, but GetType().IsArray returns false for these, and casting them to ICollection returns null as well, but casting them to IEnumerable returns a non-null value.

    So...for the time being, I am still seeking a solution that works for all cases.

提交回复
热议问题