无法使用 "Add Range" 将 Class 中的列表复制到其他 Class 中的另一个列表

Unable to use "Add Range" to copy a list in a Class to another list in other Class

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    class mylist
    {
        public List<string> list1 = new List<string>();
    }

    class mylist2
    {
        public List<string> list2 = new List<string> { "aton", "electron" };
        public void listconvert()
        {
            mylist ml = new mylist();
            ml.list1.AddRange(list2);
            MessageBox.Show("do you kn ow");
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        mylist2 ml2 = new mylist2();
        ml2.listconvert();
        mylist ml = new mylist();

        for (int i = 0; i < ml.list1.Count; i++)
        {
            textBox1.AppendText(ml.list1[i].ToString() + "\n");
        }
    }
}

我将缩小到这些行:

        mylist2 ml2 = new mylist2();
        ml2.listconvert();
        mylist ml = new mylist();

该代码段中的第三行与该代码段中的第二行使用不同的 mylist 类型实例。然后,当您继续对 ml 变量进行交互时,您尚未对该列表执行任何操作。

也许你想要这个:

public class mylist
{
    public List<string> list1 = new List<string>();
}

public class mylist2
{
    public List<string> list2 = new List<string> { "aton", "electron" };

    public void listconvert(List<string> other)
    {
        other.AddRange(list2);
        //MessageBox.Show("do you kn ow");
    }
}

private void button1_Click(object sender, EventArgs e)
{
    mylist ml = new mylist();
    mylist2 ml2 = new mylist2();

    ml2.listconvert(ml);   
    for (int i = 0; i < ml.list1.Count; i++)
    {
        textBox1.AppendText(ml.list1[i].ToString() + "\n");
    }
}

您似乎有两个问题。

首先,这段代码创建了一个列表,但没有在任何地方存储引用,因此它实际上丢失了:

    public void listconvert()
    {
        mylist ml = new mylist();
        ml.list1.AddRange(list2);
        MessageBox.Show("do you kn ow");
    }

其次,此代码创建一个空列表,然后尝试将此空列表的元素添加到文本框中:

        mylist ml = new mylist();

        for (int i = 0; i < ml.list1.Count; i++)
        {
            textBox1.AppendText(ml.list1[i].ToString() + "\n");
        }

您可能希望将代码更改为如下所示:

    class mylist2
    {
        public List<string> list2 = new List<string> { "aton", "electron" };
        public mylist listconvert()
        {
            mylist ml = new mylist();
            ml.list1.AddRange(list2);
            MessageBox.Show("do you kn ow");
            return ml;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        mylist2 ml2 = new mylist2();
        mylist ml = ml2.listconvert();

        for (int i = 0; i < ml.list1.Count; i++)
        {
            textBox1.AppendText(ml.list1[i].ToString() + "\n");
        }
    }