Home >Backend Development >C++ >How Can I Instantiate Generic Types in C# Using Type Variables?
Create a generic type instance using a variable of the containing type
In C#, it may seem counterintuitive that you cannot instantiate a generic type directly using a variable of the containing type. The following code illustrates the problem:
<code class="language-c#">Type k = typeof(double); List<k> lst = new List<k>(); // 编译错误</code>
This code does not compile because it attempts to use the variable k to specify a generic type. However, there is a workaround that can be used to achieve the desired functionality.
To create a generic type instance using a variable of the containing type, you can leverage reflection and Activator.CreateInstance():
<code class="language-c#">var genericListType = typeof(List<>); var specificListType = genericListType.MakeGenericType(typeof(double)); var list = Activator.CreateInstance(specificListType);</code>
This code works like this:
genericListType
Gets the generic List<>
type definition. MakeGenericType()
gets the generic type definition and specifies the actual type parameters (double
in this case). Activator.CreateInstance()
Instantiates a specific generic type using the specified type parameters. The above is the detailed content of How Can I Instantiate Generic Types in C# Using Type Variables?. For more information, please follow other related articles on the PHP Chinese website!