C# 以其他形式创建/修改列表

C# 以其他形式创建/修改列表,c#,winforms,C#,Winforms,我想打开第二个窗体,创建对象,将它们添加到列表中,然后将列表返回到主窗体,但在主窗体中看不到列表中的对象 这就是我目前所拥有的 主要表格: public List<Actor> actorenlijst = new List<Actor>(); public List<Actor> getActoren() { return actorenlijst; } public void setActoren(List<Actor> actor

我想打开第二个窗体,创建对象,将它们添加到列表中,然后将列表返回到主窗体,但在主窗体中看不到列表中的对象

这就是我目前所拥有的

主要表格:

public List<Actor> actorenlijst = new List<Actor>();

public List<Actor> getActoren()
{
    return actorenlijst;
}

public void setActoren(List<Actor> actorlist)
{
    this.actorenlijst = actorlist;
}

private void button3_Click(object sender, EventArgs e)
{
    foreach (Actor actor in actorenlijst)
    {
        MessageBox.Show(actor.getName());
    } 
}
public List actorenlijst=new List();
公共列表getActoren()
{
返回actorenlijst;
}
公共void setActoren(列表actorlist)
{
this.actorenlijst=actorlist;
}
私有无效按钮3\u单击(对象发送者,事件参数e)
{
foreach(actorenlijst中的演员)
{
Show(actor.getName());
} 
}
表格2:

MainForm mainform = new MainForm();
List<Actor> actoren = new List<Actor>();

public void button1_Click(object sender, EventArgs e)
{
    actoren = mainform.getActoren();  //Doesn't work!?!
    if (actoren.Count >= 3)
    {
        MessageBox.Show("You can't add more than 3 actors.");
    }
    else 
    { 
        actoren.Add(new Actor(tbNaam.Text)); 
    }
    foreach (Actor actor in actoren)
    {
        MessageBox.Show(actor.getName()); //works correctly
    }
    mainform.setActoren(actoren); //Doesn't Work !?!
}

MainForm MainForm=new MainForm();
List actoren=新列表();
公共无效按钮1\u单击(对象发送者,事件参数e)
{
actoren=mainform.getActoren();//不工作!?!
如果(actoren.Count>=3)
{
Show(“您不能添加超过3个演员”);
}
其他的
{ 
Add(新参与者(tbNaam.Text));
}
foreach(actoren中的演员)
{
MessageBox.Show(actor.getName());//工作正常
}
mainform.setActoren(actoren);//不工作!?!
}
当我在
Form2
中询问列表中的内容时,它会告诉我想要什么,但当我在main表单中执行相同操作时,列表是空的


任何帮助都将不胜感激

创建新的
MainForm
将不起作用,因为每个实例都有自己的字段和属性。在新实例上设置
actorenlijst
不会更改另一个实例上的
actorenlijst

相反,您可以将
Nieuwe\u Actor
表单上的
actoren
替换为如下公共属性:

public List<Actor> Actoren { get; set; }

现在两个表单都引用了相同的列表,因此不需要
setActoren

MainForm MainForm=newmainform()?这是可疑的。为什么要在次窗体中创建新的主窗体?MainForm的这个实例有自己的
actorenlijst
,与“真正的”MainForm上实际可见的列表不同。我认为您的问题更多地与您创建/显示
Form2
的方式有关。您需要重新排列该代码,以便正确地将
MainForm
传递给它,或者在显示
actoren
列表后将其传回。你能发布那个代码吗?我在
MainForm
中看不到
setActoren
方法
getActorenlijst
setActorenlijst
可以被属性替换。@Blorgbeard我创建了一个新的主窗体,因为我不知道如何在第二个窗体中找到我的“真正”主窗体。我使用此代码打开第二个表单:
var form2=new Nieuwe_Actor();form2.ShowDialog()这两行都在表单中的一个按钮Click2中创建一个具有form class参数的构造函数。不要创建mainform的新实例。非常感谢!我们已经为此奋斗了几个小时:P
var form2 = new Nieuwe_Actor();
form2.Actoren = this.actorenlijst;
form2.ShowDialog();