2012-07-09 78 views
2

我想知道如何在運行時獲取非泛型IDictionary的鍵和值類型。在運行時獲取非泛型IDictionary的鍵和值類型

對於泛型IDictionary,我們可以使用反射來獲得泛型參數,已經回答了here

但對於非泛型IDictionary,例如HybridDictionary,我如何獲得鍵和值類型?

編輯:我可能沒有正確描述我的問題。 對於非泛型IDictionary的,如果我有HybridDictionary的,它被聲明爲

HyBridDictionary dict = new HyBridDictionary(); 

dict.Add("foo" , 1); 
dict.Add("bar", 2); 

我怎樣才能找到密鑰的類型是值的字符串類型是int?

回答

1

非通用詞典不一定有型的關鍵或價值相同的方式作爲一個通用字典會。他們可以將任何類型作爲關鍵字,並將任何類型作爲值。

考慮一下:

var dict = new System.Collections.Specialized.HybridDictionary(); 

dict.Add(1, "thing"); 
dict.Add("thing", 3); 

它有多種類型的鑰匙,和多種類型的值。那麼,你會說什麼類型的關鍵是?

您可以找出每個單獨的鍵和單個值的類型,但不能保證它是完全相同的類型。

2

從MSDN頁:

Msdn Link

// Uses the foreach statement which hides the complexity of the enumerator. 
    // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. 
    public static void PrintKeysAndValues1(IDictionary myCol) { 
     Console.WriteLine(" KEY      VALUE"); 
     foreach (DictionaryEntry de in myCol) 
     Console.WriteLine(" {0,-25} {1}", de.Key, de.Value); 
     Console.WriteLine(); 
    } 

    // Uses the enumerator. 
    // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection. 
    public static void PrintKeysAndValues2(IDictionary myCol) { 
     IDictionaryEnumerator myEnumerator = myCol.GetEnumerator(); 
     Console.WriteLine(" KEY      VALUE"); 
     while (myEnumerator.MoveNext()) 
     Console.WriteLine(" {0,-25} {1}", myEnumerator.Key, myEnumerator.Value); 
     Console.WriteLine(); 
    } 

    // Uses the Keys, Values, Count, and Item properties. 
    public static void PrintKeysAndValues3(HybridDictionary myCol) { 
     String[] myKeys = new String[myCol.Count]; 
     myCol.Keys.CopyTo(myKeys, 0); 

     Console.WriteLine(" INDEX KEY      VALUE"); 
     for (int i = 0; i < myCol.Count; i++) 
     Console.WriteLine(" {0,-5} {1,-25} {2}", i, myKeys[i], myCol[myKeys[i]]); 
     Console.WriteLine(); 
    } 
+0

他在詢問*類型*。您正在顯示鍵和值。 – 2012-07-09 03:03:42

+0

對不起,好點 - 看起來像麒麟的答案是去的。 – duyker 2012-07-09 03:12:10

1

試試這個:

foreach (DictionaryEntry de in GetTheDictionary()) 
{ 
    Console.WriteLine("Key type" + de.Key.GetType()); 
    Console.WriteLine("Value type" + de.Value.GetType()); 
}