public static void CreateControl(string controlTypeFullName, 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;
}
}
Type.GetType("System.Windows.Forms.CheckBox")行不行?呵呵,不行。Type.GetType()方法从字符串获得类型仅限于corlib中的类型或者工程内部的类型,如果是来自于外部的程序集就需要加以程序集的名称。Windows.Forms程序集是公有的程序集,是位于程序集缓存中的,可以在.net Framwork内部实现side by side执行。所以这个程序集有不同的版本,为了确定使用的版本,我们不仅要提供程序集的名称,还要提供程序集的版本和强名称。按照这个思路,.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程序集。
TopNamespace.SubNameSpace.ContainingClass+NestedClass, MyAssembly, Version=1.3.0.0, Culture=neutral, PublicKeyToken=b17a5c561934e089