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

查看:235
本文介绍了如何使用反射动态创建通用的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>
{ }

我想用TASKA或TaskB C#反射动态创建( Activator.CreateInstance )。不过,我不知道前手的类型,所以我需要的基础上,如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);

要看到我想出了backtick1为通用类的名字,看到本文

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天全站免登陆