Create a generic list using reflection

前端 未结 3 1455
走了就别回头了
走了就别回头了 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 02:00

    You can't instantiate an interface. What you can do is instantiate a generic type that implements that interface. In your case, you'll want to get the Type representing the generic List<>, then call MakeGenericType on it.

    That assumes that you know List will always work. If not, I suppose you could search for types that implement the interface, but how you'd pick one and be sure it has a parameterless constructor seems complicated to me. Seems like it would be easier to get the actual type of the object rather than the interface in that case.

提交回复
热议问题