反射 - 如何在指定的参数索引处获取值

时间:2011-12-09 16:18:06

标签: c# .net reflection

我正在尝试使用反射来获取属性的指定索引的值。

This answer适用于List<>类型的标准属性例如,但在我的情况下,我尝试使用的集合具有不同的格式:

public class NumberCollection : List<int>
{
    public NumberCollection()
    {
        nums = new List<int>();
        nums.Add(10);
    }

    public new int this[int i]
    {
        get { return (int) nums[i]; }
    }

    private List<int> nums;

}

public class TestClass
{
    public NumberCollection Values { get; private set; }

    public TestClass()
    {
        Values = new NumberCollection();
        Values.Add(23);
    }
}


class Program
{
    static void Main(string[] args)
    {
        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;
        // Code will ERROR on the next line...
        PropertyInfo pi2 = collection.GetType().GetProperty(indexerName);
        Object value = pi2.GetValue(collection, new Object[] { 0 });

        Console.Out.WriteLine("tc.Values[0]: " + value);
        Console.In.ReadLine();
    }
}

此代码提供AmbiguousMatchException(“找到不明确的匹配”。)。我知道我的收藏课程有点人为,但任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

一种选择是使用

var prop = Type.GetProperties()
               .Where(prop => prop.DeclaringType == collection.GetType())
               .First();

如果需要,可以将Collection.GetType()更改为其他类型。但基本上是:遍历属性而不是使用Type.GetProperty

答案 1 :(得分:0)

如果您要查找所有默认成员,可以要求Type.GetDefaultMembers(),然后检查成员以找到您要查找的成员。

或者,如果您知道索引器的数据类型,则可以使用类型数组说明符调用GetPropertyInfo

相关问题