Home >Backend Development >C++ >How Can I Dynamically Create Generic Objects in C# Using Reflection?

How Can I Dynamically Create Generic Objects in C# Using Reflection?

DDD
DDDOriginal
2025-01-22 09:32:09744browse

How Can I Dynamically Create Generic Objects in C# Using Reflection?

Use reflection to dynamically create generic objects in C#

In C#, we often encounter situations where we need to dynamically create objects based on type strings. This approach uses reflection to avoid explicit type declarations.

Consider the following class structure:

<code class="language-csharp">public class Item
{ }

public class Task<T>
{ }

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

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

Our goal is to use reflection to dynamically create an instance of TaskA or TaskB. Since the type is not known in advance, we will rely on the type string, such as "namespace.TaskA" or "namespace.TaskAB".

Using reflection, we can achieve it as follows:

<code class="language-csharp">var type = Type.GetType("namespace.TaskA`1"); // 将“namespace”替换为您实际的命名空间
Type[] typeArgs = { typeof(Item) };
var makeme = type.MakeGenericType(typeArgs);
object instance = Activator.CreateInstance(makeme);</code>

This method dynamically creates an instance of TaskA based on the specified type string. If a generic class accepts multiple types, be sure to include the comma when omitting the type name, as in the following example:

<code class="language-csharp">Type type = typeof(IReadOnlyDictionary);</code>

The above is the detailed content of How Can I Dynamically Create Generic Objects in C# 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