<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>
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>
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!