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)
Fra*_*uma 16
首先使用获取Type对象 Type.GetType(stringContainingTheGenericTypeArgument)
然后typeof(Repository<>).MakeGenericType(theTypeObject)用来获得泛型类型.
最后用 Activator.CreateInstance
| 归档时间: |
|
| 查看次数: |
19946 次 |
| 最近记录: |