简体   繁体   English

如何使用c#中的反射向字典添加值?

[英]How to add a value to a 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 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 如果您需要获取单元测试的字段和值,请考虑使用Microsoft的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. 然后,您可以从Dictionary中自由获取和设置所需的任何值。

if(field != null)
{
   field.GetValue(instance);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM