【发布时间】:2025-12-06 03:45:02
【问题描述】:
我有这个简短的 Windows 窗体应用程序代码,我无法正常工作。它使用类的实例(作为临时存储位置)来填充相同类类型的数组。它有一个按钮和一个文本框。如果按下按钮,文本将保存在 Name 成员中并添加到数组中。 如果 Name 被另一个数组成员占用,它应该显示一条消息“名称被占用!”而不是将其添加到数组中。问题是这个条件检查总是正确的! 如果我们输入“Marry”,调试器会显示
if (examleArray[i].Name == temp.Name)
相当于:
if ("Marry" == "Marry")
好像一个指向另一个。为什么是这样?我如何解决它?谢谢!
namespace errorexample
{
public partial class Form1 : Form
{
example temp = new example();
example[] examleArray = new example[10];
int examleArrayIndex = 0;
bool NameTaken = false;
public Form1()
{ InitializeComponent(); }
private void button1_Click(object sender, EventArgs e)
{
temp.Name = textBox1.Text;
NameTaken = false;
for (var i = 0; i < (examleArrayIndex); i++)
{
if (examleArray[i].Name == temp.Name)
{
NameTaken = true;
MessageBox.Show("Name taken!");
}
}
if (NameTaken == false)
{
examleArray[examleArrayIndex] = temp;
examleArrayIndex++;
}
}
}
public class example {
public string Name;
}
}
【问题讨论】:
-
因为您的表单中只有一个
example实例,所以您继续重复使用它 -
因为你有一个引用数组,它们都指向同一个
example对象,因为你只创建了一个。