【问题标题】:PropertyInfo.GetValue() how do I index collection by string using reflection in C#?PropertyInfo.GetValue() 如何在 C# 中使用反射按字符串索引集合?
【发布时间】:2010-10-19 20:15:58
【问题描述】:

假设我有一个类,它有一个 NameValueCollection 属性。

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

    public TestClass()
    {
        Values = new NameValueCOllection();
        Values.Add("key", "value");
        Values.Add("key1", "value1");
    }
}

我知道如何使用 int indexer 获取 Values 集合的项目(GetProperty() 和 GetValue() 函数可以做到)。但是如何使用 .net 反射通过字符串键获取此 NameValueCollection 的项目?

【问题讨论】:

  • 你为什么要通过反射来做到这一点?

标签: .net reflection collections indexing


【解决方案1】:
NameValueCollection coll;
var indexer = typeof(NameValueCollection).GetProperty(
    "Item",
    new[] { typeof(string) }
);
var item = indexer.GetValue(coll, new [] { "key" } );

【讨论】:

  • 非常感谢,我错过了 GetValue 函数的第二个参数是 object[] :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
  • 2010-10-11
相关资源
最近更新 更多