2010-06-01 72 views
3

增加值的词典我有一个类使用反射

class a 
{ 
    private Dictionary <int , string> m_Dict = new Dictionary<int , string>(); 
} 
从其他组件/类

需要使用反射值添加到字典m_Dict!我该怎么做 ?我搜索并尝试,但没有成功。

+4

反思?给一个男人一把锤子,一切看起来像一个钉子!... – 2010-06-01 08:26:31

回答

3

我假设你要访问的私有成员 “m_Dict”?

a x = new a(); 

Dictionary dic = (Dictionary) x.GetType() 
        .GetField("m_Dict",BindingFlags.NonPublic|BindingFlags.Instance) 
        .GetValue(x); 

// do something with "dic" 

但是,这是非常糟糕的设计

+0

同意但尝试围绕EWS托管API进行一些单元测试而不这样做。 – jolySoft 2014-10-09 09:34:16

3

词典是一个痛苦,因为它不实施IList(我只是在另一个晚上呻吟)。这真的取决于你有什么可用。对于int/string解决Add方法很简单,但如果您要处理典型的列表反射,则需要使用Add方法ICollection<KeyValuePair<int,string>>

对于标准用法:

object data = new Dictionary<int, string>(); 
object key = 123; 
object value = "abc"; 
var add = data.GetType().GetMethod("Add", new[] { 
      key.GetType(), value.GetType() }); 
add.Invoke(data, new object[] { key, value });