How to find all the classes which implement a given interface?

前端 未结 6 976
栀梦
栀梦 2020-11-27 10:36

Under a given namespace, I have a set of classes which implement an interface. Let\'s call it ISomething. I have another class (let\'s call it CClass

相关标签:
6条回答
  • 2020-11-27 10:55

    You can get a list of loaded assemblies by using this:

    Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()
    

    From there, you can get a list of types in the assembly (assuming public types):

    Type[] types = assembly.GetExportedTypes();
    

    Then you can ask each type whether it supports that interface by finding that interface on the object:

    Type interfaceType = type.GetInterface("ISomething");
    

    Not sure if there is a more efficient way of doing this with reflection.

    0 讨论(0)
  • 2020-11-27 10:56
    foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
    {
        if (t.GetInterface("ITheInterface") != null)
        {
            ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
            executor.PerformSomething();
        }
    }
    
    0 讨论(0)
  • 2020-11-27 10:58

    You could use something like the following and tailor it to your needs.

    var _interfaceType = typeof(ISomething);
    var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
    var types = GetType().GetNestedTypes();
    
    foreach (var type in types)
    {
        if (_interfaceType.IsAssignableFrom(type) && type.IsPublic && !type.IsInterface)
        {
            ISomething something = (ISomething)currentAssembly.CreateInstance(type.FullName, false);
            something.TheMethod();
        }
    }
    

    This code could use some performance enhancements but it's a start.

    0 讨论(0)
  • 2020-11-27 11:03

    Maybe we should go this way

    foreach ( var instance in Assembly.GetExecutingAssembly().GetTypes().Where(a => a.GetConstructor(Type.EmptyTypes) != null).Select(Activator.CreateInstance).OfType<ISomething>() ) 
       instance.Execute(); 
    
    0 讨论(0)
  • 2020-11-27 11:06

    A working code-sample:

    var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.GetInterfaces().Contains(typeof(ISomething))
                             && t.GetConstructor(Type.EmptyTypes) != null
                    select Activator.CreateInstance(t) as ISomething;
    
    foreach (var instance in instances)
    {
        instance.Foo(); // where Foo is a method of ISomething
    }
    

    Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.

    0 讨论(0)
  • 2020-11-27 11:16

    A example using Linq:

    var types =
      myAssembly.GetTypes()
                .Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
    
    0 讨论(0)
提交回复
热议问题