在其他类

时间:2018-04-27 13:55:43

标签: c# winforms

我不是程序员,但我试着简化我的实际工作。 我有一个如下代码:

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类中被修改以获取数据。

你能告诉我应该怎么做吗?

1 个答案:

答案 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()应该检索修改后的列表