2010-04-22 54 views

回答

16

它在C#中稱爲Dictionary 。使用泛型你可以實際索引任何類型。像這樣:

Dictionary<Person, string> dictionary = new Dictionary<Person, string>(); 
Person myPerson = new Person(); 
dictionary[myPerson] = "Some String"; 
... 
string someString = dictionary[myPerson]; 
Console.WriteLine(someString); 

這明顯打印出「Some String」給控制檯。

這是字典的靈活性的示例。你可以用一個字符串作爲索引來完成,就像你所要求的一樣。

+0

葉氏,看看'System.Collections' http://msdn.microsoft.com/en-us/library/system.collections.aspx – xandercoded 2010-04-22 04:28:40

+2

@xandercoded,你可能想'System.Collections.Generic'。 'System.Collections'是.NET的非通用形式1. – Kobi 2010-04-22 04:32:53

+0

謝謝........:d – 2010-04-22 15:40:32

2
Dictionary<string, whatyouwanttostorehere> myDic = 
          new Dictionary<string, whatyouwanttostorehere>(); 
myDic.Add("Name", instanceOfWhatIWantToStore); 
myDic["Name"]; 
+0

TY ...尼斯.... – 2010-04-22 04:28:21

+1

這就是我的意思很抱歉,它沒有顯示出來完全第一次。 – 2010-04-22 04:31:52

6

數組不一樣,在C#中的工作,但你可以一個索引屬性添加到任何類:

class MyClass 
{ 
    public string this[string key] 
    { 
     get { return GetValue(key); } 
     set { SetValue(key, value); } 
    } 
} 

然後,你可以寫陳述的類型你問對這樣的:

MyClass c = new MyClass(); 
c["Name"] = "Bob"; 

這是如何實現基於字符串的索引訪問Dictionary<TKey, TValue>NameValueCollectionNameValueCollection和類似的類。您可以實現多個索引,以及,例如,一個用於索引和一個名字,你只需要添加另一個屬性與上面不同的參數類型。

內置多種框架類已經有這些索引,包括:

  • SortedList<TKey, TValue>
  • Dictionary<TKey, TValue>
  • SortedDictionary<TKey, TValue>
  • NameValueCollection
  • Lookup<TKey, TValue>(在System.Linq

...等等。這些都是爲輕微不同的目的而設計的,因此您需要閱讀每一個,並查看哪一個適合您的需求。

+0

感謝,對laters要命的答案....:d – 2010-04-22 15:44:08