2012-08-16 56 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是類型安全和性能的首選方法。