Loop over values in an IEnumerable<> using reflection

前端 未结 2 703
醉梦人生
醉梦人生 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
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 19:19

    Well, you can test it as Aghilas said and, once tested and confirmed as IEnumerable you can do something like this:

    public static bool IsEnumerable( object myProperty )
    {
        if( typeof(IEnumerable).IsAssignableFrom(myProperty .GetType())
            || typeof(IEnumerable<>).IsAssignableFrom(myProperty .GetType()))
            return true;
    
        return false;
    }
    
    public static string Iterate( object myProperty )
    {
        var ie = myProperty as IEnumerable;
        string s = string.Empty;
        if (ie != null)
        {
            bool first = true;
            foreach( var p in ie )
            {
                if( !first )
                    s += ", ";
                s += p.ToString();
                first = false;
            }
        }
        return s;
    }
    
    foreach( var p in myObject.GetType().GetProperties() )
    {
        var myProperty = p.GetValue( myObject );
        if( IsEnumerable( myProperty ) )
        {
            Iterate( myProperty );
        }
    }
    
    0 讨论(0)
提交回复
热议问题