GetValue通过反思

时间:2011-10-02 09:41:33

标签: c# reflection

我想通过循环遍历它们并使用反射来获取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());        

但我得到“对象与目标类型不匹配”错误,我很困惑,不知道要指定哪个对象作为获取值的源对象。

请指导我完成...... 提前谢谢你。

2 个答案:

答案 0 :(得分:5)

这不是反思的理由。

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

代码看起来像这样:

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

答案 1 :(得分:1)

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

相关问题