2012-08-16 52 views
0

我正在使用wpf应用程序,并且我必须将某个全局对象从一个类传递到其他类,所以我声明了该类的参数化的construtor, 我关心的是哪一个作为参数,字典或哈希表,性能会更好。
我看到这篇文章下面的代码Difference between Dictionary and Hashtable

使用哈希表字典或散列表作为类中的参数化构造函数

 public partial class Sample: Window 
     { 
     Hashtable session = new Hashtable(); 

string Path= string.Empty; 
string PathID= string.Empty; 

      public Sample(Hashtable hashtable) 
      { 
       if (session != null) 
       { 
        this.session = hashtable; 
        Path= session["Path"].ToString() 
        PathID= session["MainID"].ToString(); 
       } 
       InitializeComponent(); 
      } 
    private void Window_Loaded(object sender, RoutedEventArgs e) 
      { 
      } 
    } 
+0

'Hashtable'是类型化的,在我看来,你想要一个'的IDictionary <字符串,字符串>' ,或者更好的是,定义一个实际上代表你的设置的类 – Jodrell 2012-08-16 09:23:29

+0

字典,根据我的经验,速度更快,但只读...你可以指定一个字典,但只能从中读取,如果你想编辑数据它必须使用散列表。 – TheGeekZn 2012-08-16 09:26:22

+1

@NewAmbition:为什么是['Dictionary '](http://msdn.microsoft.com/en-us/library/xfhwa508%28v= vs.100%29.aspx)只读?从来没有... – 2012-08-16 09:28:10

回答

3

难道,

public Sample(string path, string mainId) 
{ 
    this.Path = path; 
    this.PathID = mainId; 

    InitializeComponent(); 
} 

更简单,更快,更易于阅读,带来错误的编译时间等?


,该值传递的事件更是不胜枚举,

class NumerousSettings 
{ 
    public string Path {get; set;}; 
    public string MainId {get; set;}; 
    ... 
} 

public Sample(NumerousSettings settings) 
{ 
    if (settings == null) 
    { 
     throw new CallTheDefaultContructorException(); 
    } 

    this.Path = settings.Path; 
    this.PathID = settings.MainId; 
    ... 

    InitializeComponent(); 
} 
+0

为了简单起见,我已经展示了对象,gonaa在散列表中有两个以上的项目 – Buzz 2012-08-16 09:46:40

+1

@Buzz,既然你现在设置了什么,你可以为它们声明一个类型。通过使用较弱的键入或不必要的序列化,您可以节省运行时间的痛苦。定义的编译类型也更快,没有查找时间。 – Jodrell 2012-08-16 10:00:58

1

我看到这篇文章Difference between Dictionary and Hashtable

OK,以及马克的回答似乎有相当清楚的。 ..

如果您是.NET 2.0或ab奥雅纳,你应该更喜欢词典(以及其他泛型集合)

一个微妙但重要的区别是,Hashtable的支持与单个写线程多读线程,而字典不提供线程安全。如果您需要使用通用字典的线程安全性,则必须实现自己的同步,或者(在.NET 4.0中)使用ConcurrentDictionary。

如果你不需要线程安全的,则Dictionary是类型安全和性能的首选方法。