2016-12-02 36 views
2

我有这个简短的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; 
    } 

} 
+7

因为在你的表单中只有一个'example'的实例,所以你会继续重用它 – harold

+1

因为你有一个引用数组,所有指向同一个'example'对象,因为你只创建一个。 – juharr

回答

1

你只有一个temp对象,并添加保持它添加到阵列中。这是相同的temp因为你从来没有创建一个new之一。我已经改写为你:

List<example> examleArray = new List<example>(); 
private void button1_Click(object sender, EventArgs e) 
{ 
    if (examleArray.Any(e=>e.Name == textBox1.Text)) 
    { 
    MessageBox.Show("Name taken!"); 
    } else { 
    examleArray.Add(new example { Name = textBox1.Text }); 
    } 
} 

我也转换您的固定数组列表,所以你千万不要意外尝试,并添加11名,然后炸毁。我已经将您的搜索转换为LINQ来简化。

0

click事件中移动临时对象初始化,否则你正在更新同一对象

private void button1_Click(object sender, EventArgs e) 
     { 
      example temp = new example(); 
      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++; 
      } 
     } 

您可以使用列表

List<string> example = 
     new List<string>(); 

if(example.Contains(textBox1.Text)) 
{ 
    MessageBox.Show("Name taken!"); 
}else 
{ 
    example.Add(textBox1.Text); 
} 
0

您只能创建一个example对象。您将多个对同一个对象的引用放入数组中。一种解决方案是创建一个新的example对象把数组:

public class example { 
    public string Name; 
    public example(string name){ 
     Name = name; 
    } 
} 

//... 
examleArray[examleArrayIndex] = new example(temp.Name); 
相关问题