【问题标题】:Get all classes from a namespace that implements certain interface using System.Reflection [duplicate]使用 System.Reflection 从实现特定接口的命名空间中获取所有类
【发布时间】:2013-12-24 18:57:43
【问题描述】:

我在一个命名空间中有多个实现某个接口的类,我想列出所有匹配同一个接口的类。

有没有办法使用System.Reflection 来达到这个目的?

public interface A
{}
public class AB : A
{}
public class AC : A
{}
public class AD : A
{}

List<A> classList = { AB, AC, AD};

谢谢。

【问题讨论】:

    标签: c# class interface namespaces


    【解决方案1】:

    试试这个

                var interfaceType = typeof(A);
                var classes = AppDomain.CurrentDomain.GetAssemblies()
                    .SelectMany(s => s.GetTypes())
                    .Where(interfaceType.IsAssignableFrom).ToList();
                classes.Remove(typeof(A));
    

    【讨论】:

      【解决方案2】:

      是的。您需要知道这些类型在哪个程序集中。然后从该程序集中获取类型,并找到实现您的接口的类型。

      Assembly a = typeof(A).Assembly;
      var list = a.GetTypes().Where(type => type != typeof(A) && typeof(A).IsAssignableFrom(type)).ToList();
      

      【讨论】:

        【解决方案3】:

        是的,请参阅 Type.implementsInterface 了解更多信息。 http://msdn.microsoft.com/en-us/library/bb383789(v=vs.100).aspx

        你也可以使用 typeof(IWhateverable).IsAssignableFrom(myType)

        更多信息来自这里: http://www.hanselman.com/blog/DoesATypeImplementAnInterface.aspx

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-13
          • 2014-05-10
          • 2010-09-25
          • 2011-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多