How to get the type of T from a member of a generic class or method?

前端 未结 16 1951
梦毁少年i
梦毁少年i 2020-11-22 02:37

Let say I have a generic member in a class or method, so:

public class Foo
{
    public List Bar { get; set; }

    public void Baz()
    {         


        
16条回答
  •  旧时难觅i
    2020-11-22 03:23

    (note: I'm assuming that all you know is object or IList or similar, and that the list could be any type at runtime)

    If you know it is a List, then:

    Type type = abc.GetType().GetGenericArguments()[0];
    

    Another option is to look at the indexer:

    Type type = abc.GetType().GetProperty("Item").PropertyType;
    

    Using new TypeInfo:

    using System.Reflection;
    // ...
    var type = abc.GetType().GetTypeInfo().GenericTypeArguments[0];
    

提交回复
热议问题