3

実行時に非ジェネリックIDictionaryのキーと値の型を取得するにはどうすればよいのでしょうか。

ジェネリックIDictionaryの場合、リフレクションを使用してジェネリック引数を取得できます。これはここで回答されています。

しかし、HybridDictionaryなどの非ジェネリックIDictionaryの場合、キーと値の型を取得するにはどうすればよいですか?

編集:問題を適切に説明できない場合があります。非ジェネリックIDictionaryの場合、HyBridDictionaryがある場合、これは次のように宣言されます。

HyBridDictionary dict = new HyBridDictionary();

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

キーのタイプが文字列で、値のタイプがintであることを確認するにはどうすればよいですか?

4

3 に答える 3

2

msdnページから:

Msdnリンク

 // 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();
   }
于 2012-07-09T02:59:45.097 に答える
1

これを試して:

foreach (DictionaryEntry de in GetTheDictionary())
{
    Console.WriteLine("Key type" + de.Key.GetType());
    Console.WriteLine("Value type" + de.Value.GetType());
}
于 2012-07-09T03:03:09.700 に答える
1

非ジェネリックディクショナリは、ジェネリックディクショナリと同じタイプのキーまたは値を持っているとは限りません。それらは、キーとして任意のタイプを取り、値として任意のタイプを取ることができます。

このことを考慮:

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

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

複数のタイプのキーと複数のタイプの値があります。では、キーはどのタイプだと思いますか?

個々のキーと個々の値のタイプを確認できますが、すべて同じタイプであるという保証はありません。

于 2012-07-09T03:03:44.547 に答える