Accessing a Collection Through Reflection

前端 未结 9 2137
时光说笑
时光说笑 2020-12-14 00:39

Is there a way to iterate (through foreach preferably) over a collection using reflection? I\'m iterating over the properties in an object using reflection, and when the pr

9条回答
  •  时光取名叫无心
    2020-12-14 01:05

    Just get the value of the property and then cast it into an IEnumerable. Here is some (untested) code to give you an idea:

    ClassWithListProperty obj = new ClassWithListProperty();
    obj.List.Add(1);
    obj.List.Add(2);
    obj.List.Add(3);
    
    Type type = obj.GetType();
    PropertyInfo listProperty = type.GetProperty("List", BindingFlags.Public);
    IEnumerable listObject = (IEnumerable) listProperty.GetValue(obj, null);
    
    foreach (int i in listObject)
        Console.Write(i); // should print out 123
    

提交回复
热议问题