Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

c# - Which Collection Class to use: Hashtable or Dictionary?

I need to define a class with an internal collection object to hold different types of values(such as string, int, float, DateTime, and bool) by a string key. I could use Hashtable since it is not strongly typed collection class, while the Dictionary is used for strongly typed items (I could use object for Dictionary even though).

Here is the case I would like to define my class and its usage:

 public class MyBaseClass<D> {
   protected Hashtable ht = new Hashtable();

   MyClass public SetValue<T>(string key, T value)
   {
       ht.Add(key, value);
       return this;
   }

   public abstract D GetObject();
 }

 // Example of using the base class for data as class Data1
 public MyClass<Data1> : MyBaseClass<Data1> {
      public Data1 GetObject() {
         return new Data1 {
             Property1 = ht["key1"] as string,
             Property2 = Int.Parse(ht["key2"].ToString())
          }
 }

With above example, I am not sure what is the best collection to hold my data in MyBaseClass? I read some articles about Hashtable. It is an obsolete collection and the performance comparing to Dictionary collection is much slower. Should I use Dictionary or any other collection available in .Net 3.5?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Personally I'd use Dictionary<string, object> in this case. At the very least this will stop you from trying to use a non-string key.

I would personally stop using a protected field as well - consider adding an indexer to your base class with a protected setter and a public getter:

public object this[string key]
{
    get { return ht[key]; }
    protected set { ht[key] = value; }
}

If you want it to return null on access by missing key, you should use TryGetValue in the getter. Likewise you could use Add in the setter if you want to fail on duplicate key addition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...