我有这门课(摘自网):
class SingletonFormProvider
{
static Dictionary<Type, Form> mTypeFormLookup = new Dictionary<Type, Form>();
static public T GetInstance<T>(Form owner)
where T : Form
{
return GetInstance<T>(owner, null);
}
static public T GetInstance<T>(Form owner, params object[] args)
where T : Form
{
if (!mTypeFormLookup.ContainsKey(typeof(T)))
{
Form f = (Form)Activator.CreateInstance(typeof(T), args);
mTypeFormLookup.Add(typeof(T), f);
f.Owner = owner;
f.FormClosed += new FormClosedEventHandler(remover);
}
return (T)mTypeFormLookup[typeof(T)];
}
static void remover(object sender, FormClosedEventArgs e)
{
Form f = sender as Form;
if (f == null) return;
f.FormClosed -= new FormClosedEventHandler(remover);
mTypeFormLookup.Remove(f.GetType());
}
}
如果使用标准打开,我知道如何传递参数:
Form f = new NewForm(parameter); f.Show();
但我正在使用这种方式打开新表格(在上述课程的帮助下):
var f = SingletonFormProvider.GetInstance<NewForm>(this); f.Show();
那么,如何以这种方式打开新表单来传递参数?
请帮忙。
感谢。
答案 0 :(得分:0)
GetInstance<T>
方法最后有一个 params object [] 参数。它基本上说你可以继续给它参数,它们将被放入object[]
给你。
该方法在调用Activator.CreateInstance
时,将这些参数移交给表单的构造函数。
不幸的是,您的参数只会在第一次创建时传递给该子表单,而不是每次显示表单时,因为正在创建的表单与其类型相关。如果您需要在子窗体显示时设置一些值,我建议在该窗体上创建一个Initialize
方法,该方法接受您需要设置的参数。
示例强>
public class NewForm : Form
{
...
public NewForm(string constructorMessage)
{
//Shows the message "Constructing!!!" once and only once, this method will
//never be called again by GetInstance
MessageBox.Show(constructorMessage);
}
public void Initialize(string message)
{
//Shows the message box every time, with whatever values you provide
MessageBox.Show(message);
}
}
像这样调用
var f = SingletonInstanceProvider.GetInstance<NewForm>(this, "Constructing!!!");
f.Initialize("Hi there!");
f.Show();
答案 1 :(得分:0)
请参阅A Generic Singleton Form Provider for C#。你可以从中获得帮助。