开发者

GetValue by reflection

开发者 https://www.devze.com 2023-04-10 05:53 出处:网络
i want to get each ToolStripMenuItem of my MDI form\'s value by looping through them and using reflection as following:

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 ite开发者_如何学Pythonm 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.


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);
}


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

0

精彩评论

暂无评论...
验证码 换一张
取 消