如何在 C# 中使用反射向字典添加值?

发布于 2024-10-19 20:00:40 字数 336 浏览 0 评论 0原文

我有以下字典:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尸血腥色 2024-10-26 20:00:40
MethodInfo mi = field.FieldType.GetMethodInfo("set_Item");
Object dict = field.GetValue(ProjectInformation.SourceManager);
mi.Invoke(dict, new object[] {"key", 0.0} );
MethodInfo mi = field.FieldType.GetMethodInfo("set_Item");
Object dict = field.GetValue(ProjectInformation.SourceManager);
mi.Invoke(dict, new object[] {"key", 0.0} );
爱给你人给你 2024-10-26 20:00:40

如果您需要获取仅用于单元测试的字段和值,请考虑使用 Microsoft 的 PrivateObject

它在那里,因此您可以在需要时在单元测试期间检查数据成员的内部状态,这似乎是您想要做的。

在单元测试中,您可以执行以下操作:

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

然后您可以自由地从字典中获取和设置您需要的任何值。

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.

初雪 2024-10-26 20:00:40
if(field != null)
{
   field.GetValue(instance);
}
if(field != null)
{
   field.GetValue(instance);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文