problem adding object to hashtable
I am trying to call a class method dynamically depending on a condition. This is how I am doing it
I have three classes implement a single interface
interface IReadFile
{
string DoStuff();
}
The three classes A,B,C implement the interface above.
I am trying to add them to a hashtable with the code below
_HashT.Add("a", new classA());
_HashT.Add("b", new classB());
_HashT.Add("c", new classC());
This compiles fine, but gives a runtime error.{Object reference not set to an instance of an object.}
I was planning to return the correct class to the interface type d开发者_运维知识库epending on a parameter that matches the key value. say if I send in a. ClassA is returned to the interface type and the method is called.
IReadFile Obj = (IReadFile )_HashT["a"].GetType();
obj.DoStuff();
How do I correct the part above where the objects need to be added to the hashtable? Or do I need to use a different approach? All the classes are in the same assembly and namespace.
Thanks for your time.
As a guess, you have not instantiated your _HashT
object.
You need somewhere in your code (declaration or constructor probably) to instantiate it:
HashTable _HashT = new HashTable();
If you do not do this, _HashT
will be null
and an attempt to add
to it will fail with a NullReferenceException
as you have been getting.
It appears you are seeing a NullReferenceException
. Based on the limited code you provided I would say it is likely that the _HashT
variable is not assigned. It could be possible that the exception is being generated from one of your class constructors as well.
If you use Dictionary<>
you can use the following code to add and extract objects from the hashtable.
var hashtable = new Dictionary<IReadFile>();
hashtable.Add("a", new ClassA());
hashtable.Add("b", new ClassB());
hashtable.Add("c", new ClassC());
IReadFile obj = hashtable["a"];
obj.DoStuff();
Following your approach, you do not need to call GetType()
on the value you pull out of _HashT
. The value should already be an object of type IReadFile
.
Why are you calling GetType
? The IReadFile
object is the thing you are putting in the hash. Casting a Type
object into a IReadFile
is not going to cast correctly.
精彩评论