How do I detect that an object is a generic collection, and what types it contains?

后端 未结 3 459
孤城傲影
孤城傲影 2020-12-10 04:58

I have a string serialization utility that takes a variable of (almost) any type and converts it into a string. Thus, for example, according to my convention, an integer va

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 05:38

    Re your conundrum; I'm assuming stringifyList is a generic method? You would need to invoke it with reflection:

    MethodInfo method = typeof(SomeType).GetMethod("stringifyList")
                .MakeGenericMethod(lt).Invoke({target}, new object[] {o});
    

    where {target} is null for a static method, or this for an instance method on the current instance.

    Further - I wouldn't assume that all collections are a: based on List, b: generic types. The important thing is: do they implement IList for some T?

    Here's a complete example:

    using System;
    using System.Collections.Generic;
    static class Program {
        static Type GetListType(Type type) {
            foreach (Type intType in type.GetInterfaces()) {
                if (intType.IsGenericType
                    && intType.GetGenericTypeDefinition() == typeof(IList<>)) {
                    return intType.GetGenericArguments()[0];
                }
            }
            return null;
        }
        static void Main() {
            object o = new List { 1, 2, 3, 4, 5 };
            Type t = o.GetType();
            Type lt = GetListType(t);
            if (lt != null) {
                typeof(Program).GetMethod("StringifyList")
                    .MakeGenericMethod(lt).Invoke(null,
                    new object[] { o });
            }
        }
        public static void StringifyList(IList list) {
            Console.WriteLine("Working with " + typeof(T).Name);
        }
    }
    

提交回复
热议问题