如何从一个字符串在C#中创建一个通用类? [英] How do I create a generic class from a string in C#?

查看:335
本文介绍了如何从一个字符串在C#中创建一个通用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类这样的:

I have a Generic class like that :

public class Repository<T> {...}

和我需要的实例,与串... 例如:

And I need to instance that with a string ... Example :

string _sample = "TypeRepository";
var _rep = new Repository<sample>();

我怎么能这样做?是,即使可能吗?

How can I do that? Is that even possible?

谢谢!

推荐答案

下面是我的2美分:

Type genericType = typeof(Repository<>);
Type[] typeArgs = { Type.GetType("TypeRepository") };
Type repositoryType = genericType.MakeGenericType(typeArgs);

object repository = Activator.CreateInstance(repositoryType);

在回答评论这个问题。

Answering the question in comment.

MethodInfo genericMethod = repositoryType.GetMethod("GetMeSomething");
MethidInfo closedMethod = genericMethod.MakeGenericMethod(typeof(Something));
closedMethod.Invoke(repository, new[] { "Query String" });

这篇关于如何从一个字符串在C#中创建一个通用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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