如何在 C# 中使用反射向字典添加值?
我有以下字典:
private Dictionary<string, double> averages = new Dictionary<string, double>();
现在我想使用反射来添加两个附加值。我可以检索字段信息,但我还需要做什么?
FieldInfo field = ProjectInformation.SourceManager.GetType().GetField("averages");
if (field != null)
{
//what should be here?
}
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?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您需要获取仅用于单元测试的字段和值,请考虑使用 Microsoft 的 PrivateObject
它在那里,因此您可以在需要时在单元测试期间检查数据成员的内部状态,这似乎是您想要做的。
在单元测试中,您可以执行以下操作:
然后您可以自由地从字典中获取和设置您需要的任何值。
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:
Then you are free to get and set any values you need to from the Dictionary.