Home > Backend Development > C++ > Can Generic Classes Be Instantiated with Runtime-Determined Type Parameters?

Can Generic Classes Be Instantiated with Runtime-Determined Type Parameters?

DDD
Release: 2025-02-01 12:31:10
Original
728 people have browsed it

Can Generic Classes Be Instantiated with Runtime-Determined Type Parameters?

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
Copy after login

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);
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template