我有一个泛型类这样的:
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" });