Home >Backend Development >C++ >How Can I Dynamically Create a Generic Type Instance at Runtime?
In some cases, it may be necessary to dynamically create instances of a generic type based on a type determined at runtime. This can be challenging because generic types are usually defined at compile time.
One way to achieve this is to utilize reflection. Here is a workaround that allows you to create a generic type instance using a variable containing the target type:
<code class="language-csharp">Type k = typeof(double); Type genericListType = typeof(List<>); // 注意这里<> var specificListType = genericListType.MakeGenericType(k); var list = Activator.CreateInstance(specificListType);</code>The
MakeGenericType
method accepts a single Type
parameter and returns a new Type
object that represents a generic type with the specified type parameter. In this case, we pass in double
of Type
to specify the target type.
After obtaining the specific generic type, we can use the Activator.CreateInstance
method to instantiate an object of this type. This method uses reflection to dynamically create a new instance of the specified object type.
With this approach, you can dynamically create instances of generic types based on types determined at runtime, allowing for greater flexibility and code adaptability. Note that typeof(List)
needs to be changed to typeof(List<>)
to correctly represent the generic type List<T>
.
The above is the detailed content of How Can I Dynamically Create a Generic Type Instance at Runtime?. For more information, please follow other related articles on the PHP Chinese website!