Home >Backend Development >C++ >Can I Instantiate a Generic Class with a Type Parameter from a String?

Can I Instantiate a Generic Class with a Type Parameter from a String?

DDD
DDDOriginal
2025-02-01 12:26:14211browse

Can I Instantiate a Generic Class with a Type Parameter from a String?

Pass an Instantiated System.Type as a Type Parameter for a Generic Class

It is desired to know if it is possible to instantiate a generic class with a specific type parameter obtained from a string representation of the type name. In other words, can one construct the following scenario:

string typeName = <read type name from somewhere>;
Type myType = Type.GetType(typeName);

MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();

where MyGenericClass is defined as

public class MyGenericClass<T>

The compilation will fail with the error "'The type or namespace 'myType' could not be found'". To overcome this, reflection can be leveraged. Below is a fully functional example:

using System;
using System.Reflection;

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);
    }
}

Alternatively, if the generic class accepts multiple type parameters, it is crucial to specify the commas when omitting the type names. For instance:

Type genericClass = typeof(IReadOnlyDictionary<,>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);

The above is the detailed content of Can I Instantiate a Generic Class with a Type Parameter from a String?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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