简体   繁体   中英

Problem accessing class method

I am practising c# with a phonebook example using Hashtable.

I have a class which have 2 simple methods below, somehow if I use my form method to access the class, I won't be able to get a search result but if I call it within the class I am able to, I have added in a count to check if there's any item in the pPhonebook and it's always 0 when accessed outside outside, appreciate if someone can point out my mistake, does it have something to do with my Hashtable declaration? Thanks.

public class Phonebook
{
    public Hashtable pPhoneBook = new Hashtable();

    public void AddContactInfo(string perName, string perContact)
    {
        pPhoneBook.Add(perName, perContact);
        SearchContactInfo(perName); // This is okay
    }

    public void SearchContactInfo(string perName)
    {
        MessageBox.Show(pPhoneBook.Count.ToString());
        if (pPhoneBook.ContainsKey(perName))
        {
            string value = (string)pPhoneBook[perName];
            MessageBox.Show(value);
        }
        else
        {
            MessageBox.Show("Not Found");
        }

    }

Form:

private void txtSearch_Click(object sender, EventArgs e)
{
    if (textBox3.Text != "")
      {
        Phonebook pB = new Phonebook();
        pB.SearchContactInfo(textBox3.Text); // Not Okay
      }
      else
      {
        MessageBox.Show("Please fill in the Name field");
      }
}

private void txtAdd_Click(object sender, EventArgs e)
{
      if (textBox1.Text != "" & textBox2.Text != "")
      {
          Phonebook pB = new Phonebook();
          pB.AddContactInfo(textBox1.Text, textBox2.Text);
          textBox1.Text = "";
          textBox2.Text = "";
      }
      else
      {
          MessageBox.Show("Please fill in both Name and Contact field");
      }
}

这是因为,您正在创建2个不同的电话簿实例

In the search click, it appears that you are creating a new instance of teh phone book each time. So it is created new and empty. Nothing you added to it is retained. You should look in to making sure its always searching a single instance of your PhoneBook from your form.

我认为这是因为您的电话簿是空的,没有人,所以它没有返回任何结果。

You are getting 0 because your hash table is empty. You should call AddContactInfo method first, and than SearchContactInfo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM