开发者

Object Creation: How to preserve control in place of keyword 'new'

I want to add value in a Hashtable which is used by two functions when I use 'new' keyword all the values of Hashtable become zero or the table become empty. I m using the following code:

Hashtable ht; 

public void AddToList(string ItemNo)
{
    ht = Hashtable();
    ht.Add(ItemNo, ItemNo);
    // Below lines are on开发者_运维问答ly for testing
    IDictionaryEnumerator en = ht.GetEnumerator();
    while (en.MoveNext())
    {
        string str = en.Value.ToString();
        MessageBox.Show(str);
    }
}

And for removing the data I use:

public void RemoveFromList(string ItemNo)
{
    Hashtable ht = new Hashtable();
    ht.Remove(ItemNo);
}

I suppose I have to use the keyword 'preserve' or something like this instead of new keyword.


You should not create a new HashTable inside the Add method.

Replace with something like:

Hashtable ht = new HashTable();  // create 1x
public void AddTOList(string ItemNo)
{
    ht.Add(ItemNo, ItemNo);
}

The code you posted would be valid when using for instance a DataContext, because that's just a portal to a backingstore. Your Hashtable is the backingstore, so don't create a new (empty) one each time.


Can you show the entire class?

In your RemoveFromList, you are creating a new local HashTable, instead of using the same one in AddToList. If you already created a HashTable and assigned it to ht, and if ht is a member variable of the class, then you don't need to create it every time.

If I have assumed your code correctly (please post the entire class), then just remove this line from RemoveFromList:

HashTable ht = new HashTable();


Yes, "new" will create a new object - in this case an empty Hashtable. So the solution is to only use "new" once so that you only ever create one object.

With the code you have there, the simplest way would be to change it to:

Hashtable ht = new Hashtable(); 

public void AddTOList(string ItemNo)
{
    ht.Add(ItemNo, ItemNo);
}

public void RemoveFromList(string ItemNo)
{
    ht.Remove (ItemNo);
}

However, I have to ask why you want to use a Hashtable here at all. If the actual code you are writing isn't more complicated then a generic list would probably be a better fit, or an ArrayList if you can't use a new enough version of .Net.


class FooBar
{
    private Hashtable ht = null; 

    public void AddToList(string ItemNo)
    {
        if (ht == null)
            ht = new Hashtable();

        ht.Add(ItemNo, ItemNo);    
    }

    public void RemoveFromList(string ItemNo)
    {
        if (ht == null)
            ht = new Hashtable();

        ht.Remove(ItemNo);
    }
}

or (most preferred):

class FooBar
{
    private Hashtable ht = new Hashtable();

    public void AddToList(string ItemNo)
    {
        ht.Add(ItemNo, ItemNo);    
    }

    public void RemoveFromList(string ItemNo)
    {
        ht.Remove(ItemNo);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜