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

后端 未结 3 1712
渐次进展
渐次进展 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:29

    Reflection only works on one level at a time.

    You're trying to index into the property, that's wrong.

    Instead, read the value of the property, and the object you get back, that's the object you need to index into.

    Here's an example:

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    
    namespace DemoApp
    {
        public class TestClass
        {
            public List Values { get; private set; }
    
            public TestClass()
            {
                Values = new List();
                Values.Add(10);
            }
        }
    
        class Program
        {
            static void Main()
            {
                TestClass tc = new TestClass();
    
                PropertyInfo pi1 = tc.GetType().GetProperty("Values");
                Object collection = pi1.GetValue(tc, null);
    
                // note that there's no checking here that the object really
                // is a collection and thus really has the attribute
                String indexerName = ((DefaultMemberAttribute)collection.GetType()
                    .GetCustomAttributes(typeof(DefaultMemberAttribute),
                     true)[0]).MemberName;
                PropertyInfo pi2 = collection.GetType().GetProperty(indexerName);
                Object value = pi2.GetValue(collection, new Object[] { 0 });
    
                Console.Out.WriteLine("tc.Values[0]: " + value);
                Console.In.ReadLine();
            }
        }
    }
    

提交回复
热议问题