Iterating over a System.Object Dictionary at Runtime in C#
To iterate over a System.Object that is a Dictionary in runtime using a foreach loop, you can follow these steps:
1. Declare the System.Object variable named "collection" and assign it the Dictionary object.
csharp
System.Object collection = GetDictionaryObject(); // Replace GetDictionaryObject() with your method to get the Dictionary object

2. Get the type of the collection using the GetType() method.
csharp
var collectionType = collection.GetType();

3. Check if the collection type is a generic dictionary using the IsGenericType property and the GetGenericTypeDefinition() method.
csharp
if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
{
 // The collection is a generic dictionary
 // Get the key and value types of the dictionary
 var keyType = collectionType.GetGenericArguments()[0];
 var valueType = collectionType.GetGenericArguments()[1];

 // Use reflection to get the methods of the Dictionary class
 var dictionaryMethods = typeof(Dictionary<,>).GetMethods();

 // Get the GetEnumerator method of the Dictionary class
 var enumeratorMethod = dictionaryMethods.FirstOrDefault(m => m.Name == \"GetEnumerator\");

 // Invoke the GetEnumerator method to get the Enumerator object
 var enumerator = enumeratorMethod.Invoke(collection, null);

 // Get the MoveNext method of the Enumerator object
 var moveNextMethod = enumerator.GetType().GetMethod(\"MoveNext\");

 // Get the Current property of the Enumerator object
 var currentProperty = enumerator.GetType().GetProperty(\"Current\");

 // Loop through the collection using the Enumerator
 while ((bool)moveNextMethod.Invoke(enumerator, null))
 {
 // Get the key and value of the current item
 var key = keyType.GetProperty(\"Key\").GetValue(currentProperty.GetValue(enumerator));
 var value = valueType.GetProperty(\"Value\").GetValue(currentProperty.GetValue(enumerator));

 // Do something with the key and value
 Console.WriteLine($\"Key: {key}, Value: {value}\");
 }
}

Note: In this example, we use reflection to dynamically invoke the methods and properties of the Dictionary class. This allows us to iterate over the dictionary without knowing its types at compile-time.
Make sure to replace "GetDictionaryObject()" with your own method to get the Dictionary object. Also, adjust the code inside the loop to perform the desired actions on each key-value pair.
原文地址: https://www.cveoy.top/t/topic/qaG0 著作权归作者所有。请勿转载和采集!