I have a class
class a
{
pri开发者_如何学Pythonvate Dictionary <int , string> m_Dict = new Dictionary<int , string>();
}
from some other component/class need to add values to the m_Dict dictionary using reflection! How do i do it ? i searched and tried but was not successfull.
Dictionary is a pain, since it doesn't implement IList
(something I was moaning about just the other evening). It really comes down to what you have available. Resolving the Add
method for int
/string
is easy enough, but if you are dealing with typical list reflection you'll need the Add
method from ICollection<KeyValuePair<int,string>>
.
For standard usage:
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 });
I assume you want to access the private member "m_Dict"?
a x = new a();
Dictionary dic = (Dictionary) x.GetType()
.GetField("m_Dict",BindingFlags.NonPublic|BindingFlags.Instance)
.GetValue(x);
// do something with "dic"
But this is VERY bad design
精彩评论