Home >Backend Development >C++ >How Can I Dynamically Create Generic Instances in C# Using Type Variables?
Dynamic creation of generic instances using type variables
In C#, generic types provide a convenient way to define and use data structures that can work with various data types. However, in some cases, you may need to create an instance of a generic type using a variable of the containing type.
The following code attempts to create a List
<code class="language-c#">Type k = typeof(double); List<k> lst = new List<k>();</code>
To solve this problem, you can use the following methods:
The following is the corrected code:
<code class="language-c#">var genericListType = typeof(List<>); // 注意<> var specificListType = genericListType.MakeGenericType(typeof(double)); var list = Activator.CreateInstance(specificListType);</code>
With this approach, you can dynamically create an instance of a generic type using a variable containing the Type . This flexibility allows you to handle complex data structures and scenarios where generic types need to be determined programmatically. Note the typeof(List<>)
in <>
, it indicates that this is a generic type, not a specific type.
The above is the detailed content of How Can I Dynamically Create Generic Instances in C# Using Type Variables?. For more information, please follow other related articles on the PHP Chinese website!