Home >Backend Development >C++ >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
<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!