通过反射获取值
我想通过循环遍历 MDI 表单的每个 ToolStripMenuItem 并使用反射来获取它们,如下所示:
FieldInfo[] menuitems = GetType().GetFields(BindingFlags.GetField |
BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var item in menuitems )
if (item.FieldType.Equals(typeof(ToolStripMenuItem)))
MessageBox.Show(
item.FieldType.GetProperty("Tag").GetValue(item, null).ToString());
但我收到“对象与目标类型不匹配”错误,我很困惑,不知道要指定哪个对象作为源对象来获取价值。
请引导我完成... 先感谢您。
i want to get each ToolStripMenuItem of my MDI form's value by looping through them and using reflection as following:
FieldInfo[] menuitems = GetType().GetFields(BindingFlags.GetField |
BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var item in menuitems )
if (item.FieldType.Equals(typeof(ToolStripMenuItem)))
MessageBox.Show(
item.FieldType.GetProperty("Tag").GetValue(item, null).ToString());
but i got "Object does not match target type" error, i am confused and don't know what object to specify as the source object to get value of.
please guide me through...
thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个值得反思的案例。
要获取菜单项,您应该首先获取对 ToolStrip 的引用,然后从那里迭代其
Controls
集合。代码将如下所示:
This is not a case for reflection.
To get the menuitems, you should first get a reference to your ToolStrip and from there iterate over its
Controls
collection.code would then look something like this:
使用类似
GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString()
的内容。use something like
GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString()
.