To iterate through a System.Object that is a List 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, 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 by verifying if its type is a generic type and if the generic type definition is List<>. If it is a List, we get the generic argument type (T) using the GetGenericArguments() method.

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

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

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

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

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