简体   繁体   中英

HashTable .Net exception of null instance

I'm using .Net 2.0, and I've run into a strange error:

I have a hashtable using string as keys and a class (named Market) as the value. The class contains 4 integers and 1 byte. One of the integers represents a counter which I need to increment.

I have only one element in the hashtable. It's key is "Tomo" .

I do this:

string strM = "Tomo"
MarketPlace mkt = (MarketPlace)mHash[strM];
mkt.nCter++;

In the last line I get an null reference exception, even though using the debugger I can see that the hashtable contains that instance. This code was working fine a week ago.

Locate the place where you do one of the following:

mHash[strM] = mkt;
mHash.Add(strM, mkt);

At that location, mkt is null .

Edit: This is based on the fact that you stated that you verified the Hashtable contains the key. If in fact the Hashtable did not contain the key, the following applies:

If the specified key is not found, attempting to get it returns null .

Since you're using .NET 2.0, I recommend using a Dictionary<string, Market> instead of a HashTable. It will provide type safety, and probably help you realize why you are having the issue in this case.

Are you sure you're not just looking at the key in the Hashtable, where the value is null?

For example, this works:

mHash["Tomo"] = null;
Market value = (Market)mHash["Tomo"];
value.nCounter++; // NullReferenceException

Maybe you added your instance backward.

mHash.Add(instance, "Tomo")

instead of

mHash.Add("Tomo", instance)

So when you are in debugger, it may appear as if it's listed, but the key is actually the instance and "Tomo" is the object value.

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