Create a generic list using reflection

前端 未结 3 1398
走了就别回头了
走了就别回头了 2021-01-23 01:42

I have a function that uses reflection to set properties of object A from object B. At one point, I need to instantiate a generic collection. However, I am unable to get it work

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 01:51

    One technique is to declare a static method taking the same generic arguments as the list you want to create. Then you can pull the arguments from the property to invoke the method.

    Type interfaceType = destProperty.PropertyType;
    return typeof(MyClass)
        .GetMethod("CreateList", BindingFlags.NonPublic | BindingFlags.Static)
        .MakeGenericMethod(interfaceType.GetGenericArguments())
        .Invoke(null, new object[] { });
    
    private static IList CreateList()
    {
        return new List();
    }
    

提交回复
热议问题