我不是程序员,但我试着简化我的实际工作。 我有一个如下代码:
public partial class Mainform : Form
{
public List<string> List1 = new List<string>{"nom1","nom2"};
void Method1()
{
//Get data of items from List1
}
}
public partial class Setting : Form
{
// Here, i want to modify the List1 by adding the new item
Mainform ListToModif = new Mainform();
void MethodToModify()
{
//Modify List1
}
}
现在,我想返回Mainform类,其中List1在Setting类中被修改以获取数据。
你能告诉我应该怎么做吗?
答案 0 :(得分:0)
在MainForm的设置按钮OnClick
事件中,您需要将List1
传递给Setting
类:
/* declare Setting in this scope if you are going to use it multiple times */
Setting _Setting;
private void yourButtonName_OnClick(object sender, EventArgs e)
{
/* null and disposed checking to create a new instance when necessary */
if (_Setting == null || _Setting.IsDisposed)
{
/* passing this form list to the Setting form */
_Setting = new _Setting(this.List1);
}
/* calling the form through ShowDialog will make your MainForm to
wait until Setting form is closed */
_Setting.ShowDialog();
/* setting the list value */
this.List1 = _Setting.List;
_Setting.Dispose();
}
您需要像这样修改您的设置表单
public partial class Setting : Form
{
/* auto property */
public List<string> List { get; internal set; }
public Setting(List<string> listToModify)
{
this.List = listToModify;
}
private void ModifyList()
{
/* here, you modify this.List because you assigned MainForm.List1
to this.List in the code above */
}
}
这样,当您关闭Setting
时,您的MainForm.List1
现已修改,MainForm.GetData()
应该检索修改后的列表