How to add a value to a dictionary using reflection in c#?
I have the following Dictionary:
private Dictionar开发者_运维技巧y<string, double> averages = new Dictionary<string, double>();
Now I want to use reflection to add two additional values. I can retrieve the field info, but what else do I have to do?
FieldInfo field = ProjectInformation.SourceManager.GetType().GetField("averages");
if (field != null)
{
//what should be here?
}
MethodInfo mi = field.FieldType.GetMethodInfo("set_Item");
Object dict = field.GetValue(ProjectInformation.SourceManager);
mi.Invoke(dict, new object[] {"key", 0.0} );
If you need to get the field and values just for Unit Testing consider using Microsoft's PrivateObject
Its there so you can check the internal state of data members during unit testing if you need to, which appears to be 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 are free to get and set any values you need to from the Dictionary.
if(field != null)
{
field.GetValue(instance);
}
精彩评论