我一直在使用工厂模型创建子表单以添加到MDI表单.这是我一直在使用的代码:
/// <summary>
/// This uses the Factory Model to create the child node and then add it to the MDI Parent (this)
/// </summary>
/// <param name="childName">String class name of the child, i.e. RentalEase.PropertyGrid must extend Form or SingleInstance</param>
/// <param name="singleInstance">bool If this class is to be a single instance and restricted to only on instance. Must extend SingleInstance</param>
public void createChild(string childName, bool singleInstance) {
if (singleInstance) {
try {
BaseAndSingleInstanceForm f = BaseAndSingleInstanceForm.getInstanceByType(this, Type.GetType(childName));
f.MdiParent = this;
f.Show();
f.BringToFront();
this.Refresh();
} catch (Exception ex) {
MessageBox.Show("Could not create child: " + ex.ToString());
}
} else {
try {
object o = Activator.CreateInstance(Type.GetType(childName));
if (o is Form) {
Form f = (Form)o;
f.MdiParent = this;
f.Show();
f.BringToFront();
this.Refresh();
} else {
throw new ArgumentException("Invalid Class");
}
} catch (Exception ex) {
MessageBox.Show("Could not create child: " + ex.ToString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,出现了一种情况,我必须将一个整数参数添加到特定表单的构造函数中.我怎样才能改变它并使其反映出来,同时仍然保持模式的当前易用性(或几乎).
您可以Object[]
向方法添加一个参数,该参数将表示要实例化的对象的构造函数的参数.然后,当您调用时,Activator.CreateInstance
您可以传入该数组,并Activator
尽力在您指定的类型上找到与Object
数组中的类型匹配的构造函数.
这是我的意思的简化示例:
using System;
class Program
{
static void Main()
{
Foo foo = (Foo)create("Foo", new Object[] { });
Bar bar = (Bar)create("Bar", new Object[] { "hello bar" });
Baz baz = (Baz)create("Baz", new Object[] { 2, "hello baz" });
}
static Object create(String typeName, Object[] parameters)
{
return Activator.CreateInstance(Type.GetType(typeName), parameters);
}
}
class Foo
{
public Foo() { }
}
class Bar
{
public Bar(String param1) { }
}
class Baz
{
public Baz(Int32 param1, String param2) { }
}
Run Code Online (Sandbox Code Playgroud)
我们有三种类型都有不同的构造函数 - 如果调用者负责发送类型名称,那么他们也将负责提供一个Objects
满足非默认构造函数的数组.
归档时间: |
|
查看次数: |
870 次 |
最近记录: |