在运行时任意指定对象的创建类型,甚至是用表示类型的名字的字符串创建所需的对象, .net Framwork 的反射机制给我们带来了解决问题的方法。这里,若只需要创建一般的对象,我们可以通过 System.Activator 来实现,而较复杂的我们可以通过获取构造方法来实现。
反射 Reflection 是 .net 中重要机制,通过反射,可以在运行时获得 .net 中每一个类型(包括类、结构、委派、接口、枚举)的成员,包括方法、属性、事件以及构造函数等,还可以获得每个成员的名称、限定符和参数等,有了反射,就可以对每一个类型了如指掌。如果获得了构造函数的信息,就可以直接创建对象,即使这个对象的类型在编译的时候还不知道。
///
1<summary>
2/// CreateNewControls 根据空间的名称,类型字符串,大小、位置去动态的生成一个控件
3/// </summary>
///
1<param name="targetControl"/>
控件加载到的容器
///
1<param name="ctlName"/>
生成的控件实例名称
///
1<param name="ctlType"/>
生成的控件类型字符串如(TextBox、Button等)
///
1<param name="ctlSize"/>
控件的大小
///
1<param name="ctlLocation"/>
控件的位置
///
1<returns>生成的控件实例</returns>
private Control CreateNewControls(Control.ControlCollection targetControl,string ctlName,Type ctlType, System.Drawing.Size ctlSize,System.Drawing.Point ctlLocation)
{
Control toCreate;
toCreate = (Control)System.Activator.CreateInstance(ctlType);
toCreate.Name = ctlName;
toCreate.Size = ctlSize;
toCreate.Location = ctlLocation;
targetControl.Add(toCreate);
return toCreate;
}
Size cbSize = new Size(160,40);
Point cbPoint = new Point(64,206);
Control c1 = CreateNewControls( this .Controls,"control1",Type.GetType("System.Windows.Forms.CheckBox, System.Windows.Forms, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b 77a 5c 561934e089"),cbSize,cbPoint);
c1.Text =" Check Box";
.ne tFramework 1.1 上, Type.GetType("System.Windows.Forms.CheckBox, System.Windows.Forms,Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b 77a 5c 561934e089") 。
我们如何取得所用 Windows.Form 程序集的版本和强名称?可以用 GetType(CheckBox).AssemblyQualifiedName 这样的语法,一旦得到了这些信息,我们就可以将这些信息用于其它任何控件,因为他们都来自于同一个版本 Windows.Forms 程序集。