我有这个简短的Windows窗体应用程序代码,我无法正常工作。它使用类的实例(作为临时存储位置)来填充相同类类型的数组。它有一个按钮和一个文本框。如果按下按钮,文本将保存在名称成员中并添加到阵列中。 如果名称被另一个数组成员占用,它应该显示一条消息“name taken!”而不是将它添加到数组中。问题是这种情况检查总是正确的! 如果我们在“嫁”型,调试器显示为什么我的类数组元素的行为像一个指针? (C#)
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'的实例,所以你会继续重用它 – harold
因为你有一个引用数组,所有指向同一个'example'对象,因为你只创建一个。 – juharr