如何从 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);
在评论中回答问题.
MethodInfo genericMethod = repositoryType.GetMethod("GetMeSomething");
MethidInfo closedMethod = genericMethod.MakeGenericMethod(typeof(Something));
closedMethod.Invoke(repository, new[] { "Query String" });