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

前端 未结 16 2155
梦毁少年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条回答
  •  日久生厌
    2020-11-22 03:22

    This is how i did it

    internal static Type GetElementType(this Type type)
    {
            //use type.GenericTypeArguments if exist 
            if (type.GenericTypeArguments.Any())
             return type.GenericTypeArguments.First();
    
             return type.GetRuntimeProperty("Item").PropertyType);
    }
    

    Then call it like this

    var item = Activator.CreateInstance(iListType.GetElementType());
    

    OR

    var item = Activator.CreateInstance(Bar.GetType().GetElementType());
    

提交回复
热议问题