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