如何从 C# 中的字符串创建泛型类? [英] How do I create a generic class from a string in C#?
本文介绍了如何从 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" });
这篇关于如何从 C# 中的字符串创建泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文