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

标签 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(“找到不明确的匹配项。”)。我知道我的收藏类有些做作,但有人可以帮忙吗?

最佳答案

一种选择是使用

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

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

关于c# - 反射 - 如何在参数的指定索引处获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448433/

相关文章:

java - 使用 Proguard 后通过反射访问方法时出现 NoSuchMethodException

c# - 如何获取SQL CE数据库中的所有表名?

c# - Gridview 评估条件无法正常工作

c# - 挂接到 WPF 窗口中的 Windows 消息循环会在内部添加白色边框

c# - 如何在 .Net Framework 4.8 中使用 .Net Standard 2.1 DLL?

.net - 访问 Form 上的成员可能会导致运行时异常,因为它是 marshal-by-reference 类的字段

.net - 使用反射获取类型的静态字段值

c# - 如何在c#中将一个参数添加到当前url

.net - 是/否适用于其他文化的 WPF 确认消息框

scala - 如何隐式获取Class