Runtime Instantiation of Generic Classes
This article explores the challenge of instantiating a generic class with a type parameter determined at runtime. Directly using a runtime-determined Type
variable as a generic type parameter is impossible due to compile-time constraints. The compiler needs the concrete type at compile time.
Attempting this directly, as shown below, results in a compiler error:
string typeName = "<read type name somewhere>"; // Runtime type name Type myType = Type.GetType(typeName); MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>(); // Compiler error
The solution involves leveraging reflection. The following example demonstrates this:
using System; using System.Reflection; public class Generic<T> { public Generic() { Console.WriteLine($"T={typeof(T)}"); } } class Test { static void Main() { string typeName = "System.String"; Type typeArgument = Type.GetType(typeName); Type genericClass = typeof(Generic<>); // Note the <> here Type constructedClass = genericClass.MakeGenericType(typeArgument); object created = Activator.CreateInstance(constructedClass); } }
The crucial step is using Type.MakeGenericType()
. This method dynamically creates a new type representing a generic instance of Generic<T>
, substituting T
with the runtime typeArgument
. Activator.CreateInstance()
then instantiates this newly constructed type. Note the use of Generic<>
to specify the open generic type.
The above is the detailed content of Can Generic Classes Be Instantiated with Runtime-Determined Type Parameters?. For more information, please follow other related articles on the PHP Chinese website!