创建基于一个类型变量的通用对象 [英] Creating a generic object based on a Type variable

查看:147
本文介绍了创建基于一个类型变量的通用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建基于被存储在数据库中的类型的通用对象。我怎样才能达致这?下面的代码(这不会编译)解释了我的意思是:



 字符串typeString = GetTypeFromDatabase(键); 
型的objectType = Type.GetType(typeString);

//这不会工作,但你的想法!
&MyObject的LT;的objectType>为MyObject =新MyObject来<&的objectType GT;();

是否有可能做这种事?



感谢


解决方案

 类型类型= ty​​peof运算(为MyObject<>)。 MakeGenericType(的objectType); 
对象myObject的= Activator.CreateInstance(类型);



此外 - 注意; Type.GetType(字符串)只检查执行的程序集和一些系统组件;它不会扫描的一切。如果您使用的程序集限定名,你应该罚款 - 否则你可能需要获得大会第一,并使用 someAssembly.GetType(串)


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

解决方案

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).

这篇关于创建基于一个类型变量的通用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆