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

前端 未结 6 1024
栀梦
栀梦 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.

提交回复
热议问题