how to iterate an SystemObject where its a List in runtime in foreach loop you shouldnt use non-generic collectionsSystemObject collection = GetDMyObject;var collectionType = collectionGetType;if coll
To iterate through a System.Object that is a List
-
Get the System.Object collection using the GetDMyObject() method.
-
Get the type of the collection using the GetType() method.
-
Check if the collection type is a generic type and if the generic type definition is List<> using the IsGenericType and GetGenericTypeDefinition() methods.
-
If the collection type is a List
, you can use the foreach loop to iterate through the elements of the collection.
Here's an example implementation:
System.Object collection = GetDMyObject();
var collectionType = collection.GetType();
if (collectionType.IsGenericType && collectionType.GetGenericTypeDefinition() == typeof(List<>))
{
var listType = collectionType.GetGenericArguments()[0];
var method = typeof(Enumerable).GetMethod("Cast").MakeGenericMethod(listType);
var typedCollection = method.Invoke(null, new[] { collection });
foreach (var item in (IEnumerable)typedCollection)
{
// Iterate through the elements of the collection here
}
}
In this example, we first check if the collection is a generic List
Next, we use reflection to invoke the Cast
Finally, we iterate through the elements of the typed collection using the foreach loop
原文地址: https://www.cveoy.top/t/topic/is6Z 著作权归作者所有。请勿转载和采集!