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
Release: 2025-01-22 09:32:09
Original
828 people have browsed it

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:

public class Item
{ }

public class Task<T>
{ }

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

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

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:

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

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:

Type type = typeof(IReadOnlyDictionary);
Copy after login

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 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template