PropertyInfo.GetValue() - how do you index into a generic parameter using reflection in C#?

后端 未结 3 1713
渐次进展
渐次进展 2021-01-02 01:52

This (shortened) code..

for (int i = 0; i < count; i++)
{
    object obj = propertyInfo.GetValue(Tcurrent, new object[] { i });
}

.. is

3条回答
  •  萌比男神i
    2021-01-02 02:31

    I was most of the way there until I saw this, and I am posting this because I didn't see it anywhere else; the key was using GetValue(collection, new Object[] { i }); in the loop rather than trying to use GetValue(collection, new Object[i]); outside the loop. (You can probably ignore the "output" in my example);

    private static string Recursive(object o)
    { 
            string output="";
            Type t = o.GetType();
            if (t.GetProperty("Item") != null)
            {
                System.Reflection.PropertyInfo p = t.GetProperty("Item");
                int count = -1;
                if (t.GetProperty("Count") != null && 
                    t.GetProperty("Count").PropertyType == typeof(System.Int32))
                {
                    count = (int)t.GetProperty("Count").GetValue(o, null);
                }
                if (count > 0)
                {
                    object[] index = new object[count];
                    for (int i = 0; i < count; i++)
                    {
                        object val = p.GetValue(o, new object[] { i });
                        output += RecursiveWorker(val, p, t);
                    }
                }
           }
           return output;        
    }
    

提交回复
热议问题