Home > Backend Development > C++ > How Can I Dynamically Create a Generic Type Instance at Runtime?

How Can I Dynamically Create a Generic Type Instance at Runtime?

Patricia Arquette
Release: 2025-01-13 07:17:42
Original
216 people have browsed it

How Can I Dynamically Create a Generic Type Instance at Runtime?

Dynamicly create instances of generic types 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>
Copy after login
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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template