【问题标题】:Get controls that implement an interface using Linq?获取使用 Linq 实现接口的控件?
【发布时间】:2015-05-09 05:36:36
【问题描述】:

我有许多从通用基类继承的控件,并且这个类实现了一个接口IMyInterface

到目前为止我尝试过:

var results = from c in this.Controls.Cast<Control>()
              where c.GetType().GetInterfaces().Contains(typeof(IMyInterface))
              select c as IMyInterface;

但是,即使它应该返回任何结果,上述内容也不会返回。

如何使用 Linq 获取实现此接口的表单上的控件列表?

【问题讨论】:

    标签: c# winforms linq


    【解决方案1】:

    如果我理解正确,你基本上可以使用:

    var results = this.Controls.OfType&lt;BaseGeneric&gt;().ToList();

    【讨论】:

    • OfType&lt;IMyInterface&gt;.
    【解决方案2】:

    给定以下扩展方法:

    public static class TypeExtensions
    {
        public static IEnumerable<Type> BaseTypesAndSelf(this Type type)
        {
            while (type != null)
            {
                yield return type;
                type = type.BaseType;
            }
        }
    }
    

    你想要这样的东西:

            var result = from c in this.Controls.Cast<Control>()
                         where c.GetType().BaseTypesAndSelf().Any(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BaseGeneric<>))
                         select c;
    

    您可能希望您的BaseGeneric&lt;T&gt; 继承自一些更抽象的BaseGenericBase,或者实现一些非泛型IBaseGeneric 接口,以使这类事情变得更简单。

    【讨论】:

      【解决方案3】:
      class Program
      {
          static void Main(string[] args)
          {
      
              A test1 = new A();
              B test2 = new B();
              C test3 = new C();
      
              List<object> test4 = new List<object>() { test1, test2, test3 };
              List<object> test5 = test4.FindAll(x => x is A).ToList();
      
          }
      }
      
      public class A
      {
      
          public A() { }
      
      }
      
      public class B
      {
      
          public B() {}
      
      
      }
      
      public class C : A
      {
      
          public C()
              :base()
          {
      
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-23
        • 1970-01-01
        • 1970-01-01
        • 2011-10-24
        相关资源
        最近更新 更多