2010-10-19 50 views
0

比方说,我有一个类,它有一个NameValueCollection属性。PropertyInfo.GetValue()如何通过C#中的反射使用字符串索引集合?

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

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

我知道怎么去使用INT索引(的getProperty()和getValue()函数可以做到这一点)Values集合的项目。但是,我怎样才能通过使用.net反射的字符串键来获得这个NameValueCollection的项目?

+0

你为什么要通过反射来做到这一点? – explorer 2010-10-19 20:20:03

回答

2
NameValueCollection coll; 
var indexer = typeof(NameValueCollection).GetProperty(
    "Item", 
    new[] { typeof(string) } 
); 
var item = indexer.GetValue(coll, new [] { "key" }); 
+0

非常感谢,我错过了GetValue函数的第2个参数是object [] :) – deff 2010-10-20 07:15:23