如何从C#中的字符串创建泛型类?

Pau*_*aul 16 .net c# generics reflection

我有一个像这样的Generic类:

public class Repository<T> {...}
Run Code Online (Sandbox Code Playgroud)

我需要用字符串来实例...示例:

string _sample = "TypeRepository";
var _rep = new Repository<sample>();
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?这甚至可能吗?

谢谢!

ale*_*lex 24

这是我的2美分:

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

object repository = Activator.CreateInstance(repositoryType);
Run Code Online (Sandbox Code Playgroud)

回答评论中的问题.

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

  • 与使用反射在运行时仅知道的类型创建存储库的方式相同.你需要灵活性,你需要付出代价. (2认同)

Fra*_*uma 16

首先使用获取Type对象 Type.GetType(stringContainingTheGenericTypeArgument)

然后typeof(Repository<>).MakeGenericType(theTypeObject)用来获得泛型类型.

最后用 Activator.CreateInstance