[英]GetValue by reflection
i want to get each ToolStripMenuItem of my MDI form's value by looping through them and using reflection as following: 我想通过遍历它们并使用反射来获取我的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());
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. 要获取菜单项,您应该首先获得对您的ToolStrip的引用,然后从中迭代其Controls
集合。
code would then look something like this: 代码如下所示:
foreach(Control ctrl in _myToolStrip.Controls)
{
MessageBox.Show(ctrl.Tag);
}
使用类似GetProperty("Tag").GetGetMethod().Invoke (item, null).ToString()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.