To iterate through a System.Object that is a List<T> in runtime using a foreach loop, you can follow these steps:

  1. Get the System.Object collection using the GetDMyObject() method.

  2. Get the type of the collection using the GetType() method.

  3. Check if the collection type is a generic type and if the generic type definition is List<> using the IsGenericType and GetGenericTypeDefinition() methods.

  4. If the collection type is a List<T>, 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&lt;&gt;))
{
    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<T> by verifying if its type is a generic type and if the generic type definition is List<>. If it is a List<T>, we get the generic argument type (T) using the GetGenericArguments() method.

Next, we use reflection to invoke the Cast<T> method from the Enumerable class, passing the collection as an argument. This method casts the collection to IEnumerable<T>, which allows us to use the foreach loop.

Finally, we iterate through the elements of the typed collection using the foreach loop.

Iterating Through a System.Object List<T> at Runtime with a Foreach Loop (Non-Generic Collections)

原文地址: https://www.cveoy.top/t/topic/qaHe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录