如何从一个字符串在C#中创建一个通用类?字符串、创建一个

2023-09-02 11:47:19 作者:青春❊就应该放肆

我有一个泛型类这样的:

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" });