patterncsharpMinor
Retrieving context menus from the form
Viewed 0 times
themenusformcontextretrievingfrom
Problem
I have the following code which is a private method inside the form and retrieve all context menus from the form. I feel, that it is not that concise as it should be. Would be grateful for any suggestions.
private IEnumerable GetContextMenus()
{
var type = this.GetType();
var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
var contextMenus = fields.Where(f => f.GetValue(this).GetType() == typeof(ContextMenuStrip));
var menus = contextMenus.Select(f=> f.GetValue(this));
return menus.Cast();
}Solution
I can't imagine why do you do this via Reflection, I believe the same can be done by walking through
Can be replaced with:
Controls tree. Your method will not work if context menu has property Generate member set to false in designer.var contextMenus = fields.Where(f => f.GetValue(this).GetType() == typeof(ContextMenuStrip));
var menus = contextMenus.Select(f=> f.GetValue(this));
return menus.Cast();Can be replaced with:
return fields.Select(f => f.GetValue(this)).OfType();Code Snippets
var contextMenus = fields.Where(f => f.GetValue(this).GetType() == typeof(ContextMenuStrip));
var menus = contextMenus.Select(f=> f.GetValue(this));
return menus.Cast<ContextMenuStrip>();return fields.Select(f => f.GetValue(this)).OfType<ContextMenuStrip>();Context
StackExchange Code Review Q#1082, answer score: 2
Revisions (0)
No revisions yet.