Reputation: 1265
I have a class
class a
{
private 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.
Upvotes: 3
Views: 4625
Reputation: 171784
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
Upvotes: 3
Reputation: 1062855
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 });
Upvotes: 5