检索具有指定类型的字段的值

时间:2011-03-02 11:39:12

标签: c# .net winforms reflection refactoring

我有以下代码,它是表单中的私有方法,并从表单中检索所有上下文菜单。我觉得,它应该是那么简洁。将不胜感激任何建议。

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

3 个答案:

答案 0 :(得分:3)

您是否乐意加入ContextMenuStrip的子类?如果是这样,我会使用:

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

如果代码在表单中,您可能希望完全避免反射,只需遍历Controls集合,如:

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

或un-LINQed变体

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