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

后端 未结 3 461
孤城傲影
孤城傲影 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条回答
  •  不知归路
    2020-12-10 05:48

    Use the Type to gather the required information.

    For generic objects, call GetType() to get their type and then check IsGenericType to find out if it is generic at all. If it is, you can get the generic type definition, which can be compared for instance like this: typeof(List<>)==yourType.GetGenericTypeDefinition(). To find out what the generic types are, use the method GetGenericArguments, which will return an array of the types used.

    To compare types, you can do the following: if (typeof(int).IsAssignableFrom(yourGenericTypeArgument)).


    EDIT to answer followup:

    Just make your stringifyList method accept an IEnumerable (not generic) as parameter and maybe also the known generic type argument, and you'll be fine; you can then use foreach to go over all items and handle them depending on the type argument if necessary.

提交回复
热议问题