通过反射获取值

发布于 2024-12-07 15:04:31 字数 482 浏览 2 评论 0原文

我想通过循环遍历 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 技术交流群。

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

发布评论

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

评论(2

梦幻的心爱 2024-12-14 15:04:31

这不是一个值得反思的案例。

要获取菜单项,您应该首先获取对 ToolStrip 的引用,然后从那里迭代其 Controls 集合。

代码将如下所示:

foreach(Control ctrl in _myToolStrip.Controls)
{
    MessageBox.Show(ctrl.Tag);
}

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:

foreach(Control ctrl in _myToolStrip.Controls)
{
    MessageBox.Show(ctrl.Tag);
}
趁微风不噪 2024-12-14 15:04:31

使用类似 GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString() 的内容。

use something like GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString() .

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文