Loop over values in an IEnumerable<> using reflection

。_饼干妹妹 提交于 2020-12-25 01:37:39

问题


Given an object possibly containing an IEnumerable<T>, how would I check that an IEnumerable<T> property exists, and if it does, loop over all values in that IEnumerable<T> using reflection, for any T?


回答1:


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
        }
    }
}



回答2:


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 );
    }
}


来源:https://stackoverflow.com/questions/12608439/loop-over-values-in-an-ienumerable-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!