在.net上用字符串动态创建控件是通过反射来实现。
首先,利用system.type.gettype方法,获得字符串中指定的控件的类型实例。
这里需要注意这个字符串的语法,根据msdn的解释:
不对数组或 com 类型执行搜索,除非已将它们加载到可用类表中。
typename 可以是简单的类型名、包含命名空间的类型名,或是包含程序集名称规范的复杂名称。
如果 typename 只包含 type 的名称,则此方法先是在调用对象的程序集中进行搜索,然后在 mscorlib.dll 程序集中进行搜索。如果 typename 用部分或完整的程序集名称完全限定,则此方法在指定的程序集中进行搜索。
assemblyqualifiedname 可以返回完全限定的类型名称(包含嵌套类型和程序集名称)。所有支持公共语言运行库的编译器将发出嵌套类的简单名称,并且当被查询时,反射依照下列约定构造一个 mangled 名称。
例如,类的完全限定名可能类似于如下形式:
topnamespace.subnamespace.containingclass+nestedclass,myassembly
但是直接使用type.gettype("system.windows.forms.textbox")获得type是null。这是因为,windows.forms程序集是公有的程序集,是位于程序集缓存中的,而这个程序集有不同的版本,为了确定使用的版本,我们不仅要提供程序集的名称,还要提供程序集的版本和强名称。照这个思路,在使用的.net framework 1.1上,将这一句写成type.gettype("system.windows.forms.checkbox, system.windows.forms, version=1.0.5000.0, culture=neutral, publickeytoken=b77a5c561934e089")。现在运行就没有问题了。问题是我们如何取得所用windows.forms程序集的版本和强名称?可以用gettype(checkbox).assemblyqualifiedname这样的语法,一旦得到了这些信息,我们就可以将这些信息用于其它任何控件,因为他们都来自于同一个版本windows.forms程序集。
利用上面说到的方法,现在就可以使用system.activator.createinstance方法来创建一个textbox控件了:
public static void createcontrol(string controltype, form form, int positionx, int positiony)
{
try
{
string assemblyqualifiedname = typeof(system.windows.forms.form).assemblyqualifiedname;
string assemblyinformation = assemblyqualifiedname.substring(assemblyqualifiedname.indexof(","));
type ty = type.gettype(controltype + assemblyinformation);
control newcontrol = (control)system.activator.createinstance(ty);
form.suspendlayout();
newcontrol.location = new system.drawing.point(positionx, positiony);
newcontrol.name = ty.name + form.controls.count.tostring();
form.controls.add(newcontrol);
form.resumelayout();
}
catch(exception ex)
{
throw ex;
}
}
调用: createcontrol("system.windows.forms.textbox", this, 10, 10);
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器