How could I get the string value from a hashtable without calling toString() methode?
开发者_运维百科example: my class:
public class myHashT : Hashtable
{
public myHashT () { }
...
public override object this[object key]
{
get
{
return base[key].ToString(); <--this doesn't work!
}
set
{
base[key] = value;
}
}
}
In an other class:
myHashT hT;
string test = hT["someKey"];
it works with hT["someKey"].toString();
but I need it without calling ToString()
and without casting to (string).
Can you just cast?
(string)hT["someKey"]
Note that if this is 2.0 or above, a generic Dictionary<string,string>
would be far simpler... and in 1.1 StringDictionary
would do the job (although IIRC you need to watch for case-insensitivity in the key).
You could use System.Collections.Generic.HashSet. Alternately use composition instead of inheritance ie. have hashtable be your private field and write your own indexer that does ToString().
public class myHashT
{
public myHashT () { }
...
private Hashtable _ht;
public string this[object key]
{
get
{
return _ht[key].ToString();
}
set
{
_ht[key] = value;
}
}
}
If i understand correctly, value in the hashtable is a string?
If so, you need to cast the object as a String.
string test = (string)hT["someKey"];
精彩评论