Create an object whose type is in a string parameter

杀马特。学长 韩版系。学妹 提交于 2019-12-24 02:44:38

问题


I have a TreeView, which contains nodes. When a user clicks on a node, corresponding CrystalReport document should be created and displayed.

For example, names of my nodes are: "PeriodReport1", "PeriodReport2", "PeriodReport3". My CrystalReport documents are named same: "PeriodReport1", "PeriodReport2", "PeriodReport3".

How can I create and display right type of crystal reports document? I could do something like this:

select case reportName
    case "PeriodReport1"
        dim myReport as new PeriodReport1
    case "PeriodReport2"
        dim myReport as new PeriodReport2
    ...
end select

But probably there is a nicer way to do this. Can I use reflection to do this?


回答1:


As long as the reports have a default paramaterless constructor, i.e. you can say new PeriodReport...

Activator.CreateInstance(Type.GetType("namespace.typename"))



回答2:


Something like this:

Type t = Type.GetType("object type name");
TBaseObj new_obj = (TBaseObj) Activator.CreateInstance(t);



回答3:


You can also stash an object of any type in the tag property of the TreeNode, which is often useful for this sort of thing. It's not very MVC, but can be a good fit if you're not already trying to keep models and views separate (which WinForms doesn't encourage you to do)




回答4:


What about casting? How do I cast a 'Object' instance? Something like

string myCustomClassName = getMyCustomClassName();
var myCustomInstance = (???????)myGenericObject; //What do I replace ?????? with?


来源:https://stackoverflow.com/questions/2272679/create-an-object-whose-type-is-in-a-string-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!