How to add value to dictionary using reflection in C #?

I have the following dictionary:

private Dictionary<string, double> averages = new Dictionary<string, double>();

Now I want to use reflection to add two additional values. I can get information about the field, but what else do I need to do?

FieldInfo field = ProjectInformation.SourceManager.GetType().GetField("averages");
if (field != null)
{
    //what should be here?
}
+3
source share
3 answers

If you need to get the field and values ​​only for Unit Testing, consider using Microsoft PrivateObject

Here you can check the internal state of data items during unit testing, if you need to, which looks like what you are trying to do.

In your unit tests, you can do the following:

MyObject obj = new MyObject();
PrivateObject privateAccessor = new PrivateObject(obj);
Dictionary<string, double> dict = privateAccessor.GetFieldOrProperty("averages") as Dictionary<string, double>;

Then you can get and set any values ​​you need from the Dictionary.

+4
source
MethodInfo mi = field.FieldType.GetMethodInfo("set_Item");
Object dict = field.GetValue(ProjectInformation.SourceManager);
mi.Invoke(dict, new object[] {"key", 0.0} );
+5
source
if(field != null)
{
   field.GetValue(instance);
}
0
source

Source: https://habr.com/ru/post/1795623/


All Articles