How to instantiate a generic list out of an unkown

2019-09-29 08:25发布

问题:

This question already has an answer here:

  • How to dynamically create generic C# object using reflection? [duplicate] 5 answers

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.