gpt4 book ai didi

c# - 在运行时获取非泛型 IDictionary 的键和值类型

转载 作者:行者123 更新时间:2023-11-30 21:06:04 26 4
gpt4 key购买 nike

我想知道如何在运行时获取非泛型 IDictionary 的键和值类型。

对于泛型IDictionary,我们可以使用反射获取泛型参数,已回答here .

但对于非泛型 IDictionary,例如 HybridDictionary,如何获取键和值类型?

编辑:我可能没有正确描述我的问题。对于非泛型 IDictionary,如果我有 HyBridDictionary,它声明为

HyBridDictionary dict = new HyBridDictionary();

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

如何知道key的类型是string,value的类型是int?

最佳答案

来自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();
}

关于c# - 在运行时获取非泛型 IDictionary 的键和值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com