C# 基于类型变量创建通用对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/955331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a generic object based on a Type variable
提问by Charlie
I need to create a generic object based on a type that is stored in a database. How can I acheive this? The code below (which won't compile) explains what I mean:
我需要基于存储在数据库中的类型创建一个通用对象。我怎样才能做到这一点?下面的代码(不会编译)解释了我的意思:
string typeString = GetTypeFromDatabase(key);
Type objectType = Type.GetType(typeString);
//This won't work, but you get the idea!
MyObject<objectType> myobject = new MyObject<objectType>();
Is it possible to do this kind of thing?
有可能做这种事情吗?
Thanks
谢谢
采纳答案by Marc Gravell
Type type = typeof(MyObject<>).MakeGenericType(objectType);
object myObject = Activator.CreateInstance(type);
Also - watch out; Type.GetType(string)
only checks the executing assembly and a few system assemblies; it doesn't scan everything. If you use an assembly-qualified-name you should be fine - otherwise you may need to get the Assembly
first, and use someAssembly.GetType(string)
.
还有——当心;Type.GetType(string)
只检查正在执行的程序集和一些系统程序集;它不会扫描所有内容。如果您使用程序集限定名称,您应该没问题 - 否则您可能需要获取第Assembly
一个,并使用someAssembly.GetType(string)
.