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
Release: 2025-02-01 12:26:14
Original
177 people have browsed it

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

where MyGenericClass is defined as

public class MyGenericClass<T>
Copy after login

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

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

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