无法在类之间传输列表中的值



我的问题是我无法在 WFA 中的两个类之间传输列表中的值

public partial class Example : Form
{
public List<string> myList = new List<string>();
private void Btn1_Click(object sender, EventArgs e)
{
new Example2().Show();
}
private void Example_Activated(object sender, EventArgs e)
{
if (myList.Count == 0)
{
//...
}
else
{
//...
}
}
public partial class Example2 : Form
{
static Example ex = new Example();
private void Btn2_Click(object sender, EventArgs e)
{
ex.myList.Add("something");
Close();
}

首先显示表单"示例"。然后我单击屏幕上的"Btn1",并出现"示例2"表单。当我在"示例 2"表单上单击"Btn2"时,myList 应该获得"某物"的新值并且"示例 2"关闭。但是这部分脚本

private void Example_Activated(object sender, EventArgs e)
{
if (myList.Count == 0)
{
//...
}
else
{
//...
}
}

显示 myList 没有值(myList.Count 等于 0(。 我能做什么?

您需要使用示例 2 表单中的数据引用现有的示例表单。static Example ex是另一个没有数据的(静态(实例。

public partial class Example : Form
{
private List<string> myList = new List<string>();
private void Btn1_Click(object sender, EventArgs e)
{
var e2 = new Example2();
e2.SetMainForm(this);
e2.Show();
}
public void AddItem(string item)
{
myList.Add(item);
}
private void Example_Activated(object sender, EventArgs e)
{
if (myList.Count == 0)
{
//...
}
else
{
//...
}
}
}
public partial class Example2 : Form
{
private Example ex;
private void Btn2_Click(object sender, EventArgs e)
{
ex.AddItem("something");
Close();
}
public void SetMainForm(Example e1)
{
ex = e1;
}
}

最新更新