开发者

Retrieving values of the fields which have specified type

开发者 https://www.devze.com 2023-02-14 03:37 出处:网络
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开发者_如何学Go concise as it should be. Would be grateful

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开发者_如何学Go concise as it should be. Would be grateful for any suggestions.

  private IEnumerable<ContextMenuStrip> 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<ContextMenuStrip>();        
    }


Are you happy to include subclasses of ContextMenuStrip? If so, I'd use:

return GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
                .Select(field => field.GetValue(this))
                .OfType<ContextMenuStrip>();


var query = (from f in GetType().GetFields(
                 BindingFlags.NonPublic | BindingFlags.Instance)
            select f.GetValue(this)).OfType<ContextMenuStrip>();


If that code is in a form, you might want to avoid reflection altogether, and just loop over the Controls collection, something like:

var controls = from Control c in Controls.AsQueryable()
               where c is ContextMenuStrip
               select c;

or the un-LINQed variant

IEnumerable<ContextMenuStrip> result = new List<ContextMenuStrip>();
foreach (var control in Controls)
{
   ContextMenuStrip menuStrip = (control as ContextMenuStrip)
   if (menuStrip != null )
   {
     result.Add(menuStrip);
   }
}
return result;
0

精彩评论

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

关注公众号