Get actual type of T in a generic List

前端 未结 4 1077
隐瞒了意图╮
隐瞒了意图╮ 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:01

    It depends on what exactly you’re asking:

    • While writing code inside a generic type Blah, how do I get the reflection type T?

      Answer: typeof(T)

    • I have an object which contains a List for some type T. How do I retrieve the type T via reflection?

      Short answer: myList.GetType().GetGenericArguments()[0]

      Long answer:

      var objectType = myList.GetType();
      if (!objectType.IsGenericType() ||
          objectType.GetGenericTypeDefinition() != typeof(List<>))
      {
          throw new InvalidOperationException(
              "Object is not of type List for any T");
      }
      var elementType = objectType.GetGenericArguments()[0];
      

提交回复
热议问题