需要动态的创建一个实例模型的时候,就用Activator.CreateInstance(Type type);如果是明确的知道要创建哪个实例的模型,就可以用 new
C#在类工厂中动态创建类的实例,所使用的方法为:
1. Activator.CreateInstance (Type)
2. Activator.CreateInstance (Type, Object[])
两种方法区别仅为:创建无参数的构造方法和创建有参数的构造函数。
private Form LoadMdiChild(Type formclass) { Form nForm = null; foreach (Form frm in this.MdiChildren) { if (frm.GetType() == formclass) { nForm = frm; break; } } if (nForm == null) { nForm = (Form)(Activator.CreateInstance(formclass,this)); //nForm.Owner = this; nForm.MdiParent = this; nForm.Left = 0; nForm.Top = 0; nForm.Dock = System.Windows.Forms.DockStyle.Fill; nForm.FormBorderStyle = FormBorderStyle.None; nForm.MaximizeBox = false; nForm.MinimizeBox = false; nForm.ControlBox = false; } return nForm; }