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>
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:
Task<T>
). new Type[] { typeof(Item) }
). Type.MakeGenericType
to generate a specific type (TaskA
or TaskB
). 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>
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>
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!