Home > Backend Development > C++ > How Can I Create a Generic Type Instance Using a Variable Holding the Type?

How Can I Create a Generic Type Instance Using a Variable Holding the Type?

Patricia Arquette
Release: 2025-01-13 06:26:42
Original
926 people have browsed it

How Can I Create a Generic Type Instance Using a Variable Holding the Type?

Create a generic <T> type instance using a variable containing the type

Creating an instance of a generic type using a variable containing the type is a useful technique in scenarios such as dynamically generating type information. While the code given in the question, which attempts to create an List<k> instance (where k is a variable of type Type ), may not compile, there are other ways to achieve this functionality.

One possible solution is to use the MakeGenericType method on the generic type definition. This method accepts a set of type parameters and returns a new type that is a version of the generic type instantiated using these parameters. In this case, the code would look like this:

<code class="language-csharp">var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));</code>
Copy after login

genericListType variables contain definitions of generic List<T> types, and MakeGenericType methods return specialized List<double> types.

After creating a specific generic type, you can use the Activator class to create instances. The CreateInstance method can be used to create an instance of a new type based on type information.

<code class="language-csharp">var list = Activator.CreateInstance(specificListType);</code>
Copy after login

The above is the detailed content of How Can I Create a Generic Type Instance Using a Variable Holding the Type?. 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