PropertyInfo.GetValue() - 如何使用C#中的反射索引到泛型参数?

fle*_*esh 13 c# generics reflection

这个(缩短的)代码..

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

..正在抛出'TargetParameterCountException:参数计数不匹配'异常.

'propertyInfo'的基础类型是某些T的集合.'count'是集合中的项目数.我需要遍历集合并对obj执行操作.

建议表示赞赏.

ang*_*son 19

反射一次仅适用于一个级别.

你试图索引该属性,这是错误的.

相反,读取属性的值和您获得的对象,这是您需要索引的对象.

这是一个例子:

using System;
using System.Collections.Generic;
using System.Reflection;

namespace DemoApp
{
    public class TestClass
    {
        public List<Int32> Values { get; private set; }

        public TestClass()
        {
            Values = new List<Int32>();
            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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 好的,我明白了,谢谢你的回复.它现在正在运作但有兴趣了解"物品"属性,如果有人知道... (2认同)