Get actual type of T in a generic List

前端 未结 4 1076
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 01:44

How do I get the actual type of T in a generic List at run time using reflection?

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-14 02:04

    You can use Type.GetGenericArguments to return the type T in a List.

    For example, this will return the Type for any List passed as an argument:

    Type GetListType(object list)
    {
        Type type = list.GetType();
        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
            return type.GetGenericArguments()[0];
        else
            throw new ArgumentException("list is not a List", "list");
    }
    

提交回复
热议问题