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

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

Barbara Streisand
Release: 2025-01-22 09:47:09
Original
390 people have browsed it

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

Use reflection to dynamically create generic C# objects

In C# development, it is often necessary to dynamically create generic objects. This creates challenges since type information is not always available. This article will explore how to solve this problem using reflection and the Activator.CreateInstance method.

Suppose we have the following class:

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

public class Task<T> { }

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

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

Our goal is to dynamically create an instance of TaskA or TaskB based on a string representing its fully qualified type name (for example, "namespace.TaskA" or "namespace.TaskB").

The solution can be achieved by following these steps:

  1. Gets the base type (Task<T>).
  2. Defines the type parameter to be supplied as an array (for example, new Type[] { typeof(Item) }).
  3. Use Type.MakeGenericType to generate a specific type (TaskA or TaskB).
  4. Use Activator.CreateInstance to instantiate generic objects.

For example, create a TaskA<Item> object using reflection:

<code class="language-csharp">var taskType = typeof(Task);
Type[] typeArgs = { typeof(Item) };
var makeme = taskType.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);</code>
Copy after login

If the type name is specified as a string, you can use the following method:

<code class="language-csharp">var taskType = Type.GetType("namespace.TaskA`1"); //注意`1`表示泛型参数个数
Type[] typeArgs = { typeof(Item) };
var makeme = taskType.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);</code>
Copy after login

This technology allows dynamic instantiation of generic objects based on type names, providing a flexible and powerful solution for handling unknown generic types at runtime. Note that the Type.GetType method requires complete namespace information, and the TaskA after the 1 indicates that the generic class has a type parameter.

The above is the detailed content of How Can I Dynamically Create Generic C# Objects Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template