I have a dynamic Type
that is generated at runtime, say myGeneratedType
. I'm trying to create an instance of the following class, where T
should be myGeneratedType
. I have come across several answers where a dynamic type had to be set to a property of a class, but cannot seem to get it to work on a List<T>
:
Type myGeneratedType;
private class Container<T>
{
public string a { get; set; }
public string b { get; set; }
public List<T> c { get; set; }
}
void Main()
{
Container<myGeneratedType> c = new Container<myGeneratedType>();
}
Obviously, the line of code in my method Main()
does not work. What should I do to create a class of Container
with my dynamic type as the generic type parameter?
Use MakeGenericType:
var type = typeof(Container<>);
var MyGenericType = type.MakeGenericType(myGeneratedType));
where myGeneratedType
is a Type
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.