Is there a way in C# to get the definition of a type from a string? I'd like to use it as a generic type parameter.
在C#中有一种方法可以从字符串中获取类型的定义吗?我想将它用作泛型类型参数。
This is what i'd like to achieve in the end.
这是我最终想要实现的目标。
string classname = "Class1"; GenericClass<Class1> gc = new GenericClass<Class1>(); gc.Method();
is there any possible way?
有什么办法吗?
1 个解决方案
#1
3
Yes, you can use reflection to do it and sometimes it cannot be too safe, try something like this article sample.
是的,您可以使用反射来执行此操作,有时它不会太安全,请尝试类似此文章的示例。
Type d1 = typeof(GenericClass<>);
Type[] typeArgs = { Type.GetType("Class1") };
Type makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
But you will not get all intellisense from visual studio.
但你不会从视觉工作室获得所有智能感知。
#1
3
Yes, you can use reflection to do it and sometimes it cannot be too safe, try something like this article sample.
是的,您可以使用反射来执行此操作,有时它不会太安全,请尝试类似此文章的示例。
Type d1 = typeof(GenericClass<>);
Type[] typeArgs = { Type.GetType("Class1") };
Type makeme = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(makeme);
But you will not get all intellisense from visual studio.
但你不会从视觉工作室获得所有智能感知。