使用Activator.Create在运行时创建Type实例困难 [英] difficullty creating an instance of Type at Run-Time using Activator.Create

查看:70
本文介绍了使用Activator.Create在运行时创建Type实例困难的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个WinForms项目,该项目定义了多个Forms.在运行时启动的主窗体中的是一个下拉列表,其中包含尚未创建实例的窗体的名称....

因此,下拉列表可能包含类似以下内容的选择列表:

TemplateForm1
TemplateForm2
TemplateForm3

在运行时:

1.可见主窗体和下拉列表:

2.用户从下拉菜单中选择一个项目.因此:现在您有了一个字符串,其中包含一个对象(窗体)的名称,例如"TemplateForm3".

3.现在,您要创建"TemplateForm3"的实例.并且,请放心:"TemplateForm3" 是当前项目中存在的表单的名称.

好像过去这种类型的代码曾经为我工作

Consider a WinForms project, that defines several Forms; in the Main Form which is launched at run-time is a drop-down containing the names of Forms which have not had an instance created ... yet.

So the drop-down may contain a selection list something like:

TemplateForm1
TemplateForm2
TemplateForm3

At run-time:

1. with Main Form and drop-down visible:

2. The user selects an item from the drop-down. So: now you have a string, containing a name of an object (the Form), like "TemplateForm3."

3. Now you want to create an instance of "TemplateForm3." And, be assured: "TemplateForm3" is the name of a Form that exists in the current Project.

Seems like in the past this type of code used to work for me

var frmType = Activator.CreateInstance(Type.GetType("TemplateForm3"));

,但是,现在我只得到一个空异常.

我想知道我是否忘记了某些要求,要么涉及此处当前程序集的必需反射(?),要么涉及使用Activator.CreateInstance的某些其他必需形式和/或GetType用法的某些变化?

我当然不希望在这里不使用反射.

而且,是的,编写一个switch/case语句很容易,使用下拉选择中的字符串以通常的方式创建新实例,但是我不想要:)

感谢你的帮助 !

谢谢,Bill

But, right now I just get a null exception.

I wonder if I have forgotten some requirement involving either required Reflection on the current assembly here (?), or some other required form of using Activator.CreateInstance and/or some variation on usage of GetType ?

I''d certainly prefer not to use Reflection here.

And, yes, it would be easy to write a switch/case statement, using the string from the drop-down selection to create new instances in the usual way, but I don'' wanna :)

Appreciate your help !

thanks, Bill

推荐答案

您必须提供完整的名称,即"namespace.TemplateForm3".

如果要使用当前运行的程序集中不存在的类型,则必须提供完全限定的类型名,即"namespace.TemplateForm2,文件名,Version = ..."
You have to supply the complete name i.e. "namespace.TemplateForm3".

If you are going to use types which are not in the current running assembly, then yo must supply the fully qualified typename i.e. "namespace.TemplateForm2, filename, Version=..."


这篇关于使用Activator.Create在运行时创建Type实例困难的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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