Home >Backend Development >C++ >Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?
Pass an Instantiated System.Type as a Type Parameter for a Generic Class
The question centers around the feasibility of constructing a generic class with an instantiated Type instance. Specifically, can one create an instance of MyGenericClass
The direct approach results in the compiler error "The type or namespace 'myType' could not be found." To overcome this limitation, reflection offers a solution.
Using reflection, one can dynamically create a type compatible with the generic class's type parameter. Here's an example:
public class Generic<T> { public Generic() { Console.WriteLine("T={0}", typeof(T)); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // MakeGenericType is badly named Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } }
Note that while the example uses a single type parameter, multiple parameters are supported. To omit a type parameter for a generic class with multiple parameters, include commas in the placeholders, as seen in the following example:
Type genericClass = typeof(IReadOnlyDictionary<>, <>); Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
The above is the detailed content of Can I Pass an Instantiated System.Type as a Generic Type Parameter in C#?. For more information, please follow other related articles on the PHP Chinese website!