Loop over values in an IEnumerable<> using reflection

前端 未结 2 729
醉梦人生
醉梦人生 2021-01-03 18:30

Given an object possibly containing an IEnumerable, how would I check that an IEnumerable property exists, and if it does, loop o

2条回答
  •  忘掉有多难
    2021-01-03 19:08

    foreach (var property in yourObject.GetType().GetProperties())
    {
        if (property.PropertyType.GetInterfaces().Contains(typeof(IEnumerable)))
        {
            foreach (var item in (IEnumerable)property.GetValue(yourObject, null))
            {
                 //do stuff
            }
        }
    }
    

提交回复
热议问题