Home >Backend Development >C++ >How to Dynamically Create Generic C# Objects Using Reflection?

How to Dynamically Create Generic C# Objects Using Reflection?

DDD
DDDOriginal
2025-01-22 09:27:10255browse

How to Dynamically Create Generic C# Objects Using Reflection?

Use reflection to dynamically create C# generic objects

In C# development, it is often necessary to dynamically create instances of generic classes. This can be achieved through reflection. A common application scenario is that the type of a generic class is not known before runtime and needs to be created based on a string representing its fully qualified name.

To use reflection to dynamically create a generic class, you need to use the Activator.CreateInstance method:

<code class="language-csharp">using System;
using System.Reflection;

public class MainClass
{
    public static void Main(string[] args)
    {
        // 获取泛型类型定义
        Type genericType = typeof(Task<>);

        // 构建泛型类型的类型参数
        Type[] typeArgs = { typeof(Item) };

        // 创建具体的泛型类型
        Type specificType = genericType.MakeGenericType(typeArgs);

        // 创建具体类型的实例
        object instance = Activator.CreateInstance(specificType);
    }
}


public class Item { }

public class Task<T> { }

public class TaskA<T> : Task<T> { }

public class TaskB<T> : Task<T> { }</code>

The above example code dynamically builds an instance of Task<Item>. If the target type is unknown at runtime, it can be built dynamically by passing the fully qualified name of the type (a string):

<code class="language-csharp">// 使用字符串表示获取类型
Type specificType = Type.GetType("namespace.TaskA`1"); // 注意 `1` 表示泛型参数个数

// 传递类型参数并创建实例
Type[] typeArgs = { typeof(Item) };
object instance = Activator.CreateInstance(specificType.MakeGenericType(typeArgs));</code>

This method allows developers to dynamically create instances of generic classes without knowing the specific type at compile time. This is particularly useful in scenarios such as inferring types from configuration files or data-driven programming.

The above is the detailed content of How to Dynamically Create Generic C# Objects Using Reflection?. 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