问题
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