如何通过传入模型名来创建对象的新实例 [英] How to create new instance of object by passing in name of model

查看:84
本文介绍了如何通过传入模型名来创建对象的新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以指出我正确的方向,



我正在编写一个前端应用程序,项目中将有大约10-15个模型。

无论您选择哪种型号,前端看起来都完全相同,唯一的区别是表中会有更多或更少的列,具体取决于您从dropDown中选择的型号。 />


我如何使用字符串,例如我点击的模型名称然后创建该模型的新实例,加载模型,然后我可以得到ojbect信息所以我可以计算属性的数量然后循环它们生成列标题,然后添加列名称(使用propertyInfo.getValue或其他东西)。?



是这个可能,我想制作通用的可重用代码。所以伪代码:



UnknownType type = new UnknownType();



getPropertyCount(type);
每个
(类型中的属性){

getAllPropertyInfo();

buildHtml();



}

Hi can anyone point me in the right direction,

i'm writing a front end application, that will have around 10-15 models in the project.
the front end will look exactly the same regardless of which model you select, the only difference being that there will be more or less columns in the table depending on which model you select from a dropDown.

how do i then use a string e.g "name of model i clicked" to then create a new instance of that model, load the model so then i can get the ojbect info so i can count the amount of properties to then loop over them generating column headers and then add the column names (using propertyInfo.getValue or something).?

is this possible, i'm wanting to make generic re-usable code. so pseudo code:

UnknownType type = new UnknownType();

getPropertyCount(type);
for each(property in type){
getAllPropertyInfo();
buildHtml();

}

推荐答案

你可以利用反射来获得你想要的类型的实例



类似这样的事情



you can make use of reflection to get instance of the type you want

something like this

(type of object)Activator.CreateInstance("name of assembly", "name of class");










Activator.CreateInstance

是你可以用来从字符串创建类的实例的.net框架中的反射程序集的一部分

is what you can use to create instance of the class from the string its part of reflection assembly in .net framework


这篇关于如何通过传入模型名来创建对象的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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