-3
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");
        }
    }
}
4

2 回答 2

0

我将其缩小到以下几行:

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

该片段中的第三行正在使用与该片段中mylist的第二行不同的类型实例。然后,当您继续对ml变量进行 interator 时,您还没有对该列表执行任何操作。

也许你想要这个:

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");
    }
}
于 2015-01-29T03:03:14.520 回答
0

您似乎有两个问题。

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

    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");
        }
    }
于 2015-01-29T03:06:53.590 回答