如何使用反射动态创建通用 C# 对象? [英] How to dynamically create generic C# object using reflection?

查看:29
本文介绍了如何使用反射动态创建通用 C# 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,我有以下对象:

In C# I have the following object:

public class Item
{ }

public class Task<T>
{ }

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

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

我想使用 C# 反射 (Activator.CreateInstance) 动态创建 TaskA 或 TaskB.但是我事先不知道类型,所以我需要根据字符串动态创建 TaskA,如namespace.TaskA"或namespace.TaskAB".

I want to dynamically create TaskA or TaskB using C# reflection (Activator.CreateInstance). However I wouldn't know the type before hand, so I need to dynamically create TaskA based on string like "namespace.TaskA" or "namespace.TaskAB".

推荐答案

查看此 文章和这个简单示例.将相同的内容快速翻译到您的课程中......

Check out this article and this simple example. Quick translation of same to your classes ...

var d1 = typeof(Task<>);
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

根据您的对于这种情况,您可以这样做...

Per your edit: For that case, you can do this ...

var d1 = Type.GetType("GenericTest.TaskA`1"); // GenericTest was my namespace, add yours
Type[] typeArgs = { typeof(Item) };
var makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);

要查看我在哪里为泛型类的名称提出反引号1,请参阅这篇文章.

To see where I came up with backtick1 for the name of the generic class, see this article.

注意:如果您的泛型类接受多种类型,则省略类型名称时必须包含逗号,例如:

Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

Type type = typeof(IReadOnlyDictionary<,>);

这篇关于如何使用反射动态创建通用 C# 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆