C# 使用单例和传递参数打开表单
我上过这门课(摘自网络): 但我使用这种方式打开新表单(在上述课程的帮助下):C# 使用单例和传递参数打开表单,c#,winforms,singleton,C#,Winforms,Singleton,我上过这门课(摘自网络): 但我使用这种方式打开新表单(在上述课程的帮助下): var f=SingletonFormProvider.GetInstance(这个); f、 Show(); 那么,如何通过这种打开新表单的方式传递参数呢 请帮忙 谢谢。GetInstance方法的末尾有一个params object[]参数。它本质上是说,您可以继续为它提供参数,它们将为您放入一个对象[] 该方法在调用Activator.CreateInstance时,将这些参数传递给表单的构造函数 不幸的是,
var f=SingletonFormProvider.GetInstance(这个);
f、 Show();
那么,如何通过这种打开新表单的方式传递参数呢
请帮忙
谢谢。GetInstance方法的末尾有一个params 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();
var f=singletonistanceProvider.GetInstance(这是“构造!!!”);
f、 初始化(“你好!”);
f、 Show();
请参阅。您可以从中获得帮助。参数是什么意思?参数、变量、对象如下:Form f=new NewForm(textBox1.Text);f、 Show();所以告诉我避免像“+1”或“谢谢”这样的评论,但我无法抗拒。。谢谢谢谢你给我链接。我从网站上得到这个课程。但mlorbetske的回答有助于提前避免一些问题
var f = SingletonFormProvider.GetInstance<NewForm>(this);
f.Show();
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();