How to instantiate a generic list out of an unkown type? [duplicate]

别等时光非礼了梦想. 提交于 2019-12-13 11:24:58

问题


I have an object as a parameter and I want to make a generic list out of that object type. Most of times I want to send a custom object type. This code declares the concept of my problem.

public void myMethod(object myObject)
{
    List<typeof(myObject)> _NewList=new List<typeof(myObject)();
}

回答1:


You could make the method generic:

public void myMethod<T>(T myObject)
{
    List<T> _NewList = new List<T>();
}

You can constrain the type to an interface or base class if your method needs to execute anything consistent on these objects.




回答2:


Via reflection:

var type = myObject.GetType();
var genericListType = typeof(List<>).MakeGenericType(new[] { type });

var list = (IList)Activator.CreateInstance(genericListType);

But it would be better to use generics.



来源:https://stackoverflow.com/questions/15661382/how-to-instantiate-a-generic-list-out-of-an-unkown-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!