Programing

주어진 인터페이스를 구현하는 모든 클래스를 찾는 방법은 무엇입니까?

lottogame 2020. 11. 14. 09:42
반응형

주어진 인터페이스를 구현하는 모든 클래스를 찾는 방법은 무엇입니까?


주어진 네임 스페이스 아래에 인터페이스를 구현하는 클래스 집합이 있습니다. 그것을라고 부르 자 ISomething. 나는 CClass알고 ISomething있지만 그 인터페이스를 구현하는 클래스에 대해 알지 못하는 또 다른 클래스를 가지고 있습니다.

CClass모든 구현을 찾고 ISomething인스턴스를 인스턴스화하고 메서드를 실행하고 싶습니다 .

누구든지 C # 3.5로 수행하는 방법에 대한 아이디어가 있습니까?


작동하는 코드 샘플 :

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 CreateInstance 호출이 성공할 수 있도록 매개 변수없는 생성자에 대한 검사를 추가했습니다.


다음을 사용하여로드 된 어셈블리 목록을 가져올 수 있습니다.

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

여기에서 어셈블리의 유형 목록을 가져올 수 있습니다 (공용 유형 가정).

Type[] types = assembly.GetExportedTypes();

그런 다음 객체에서 해당 인터페이스를 찾아 각 유형이 해당 인터페이스를 지원하는지 여부를 물어볼 수 있습니다.

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

리플렉션을 사용하여 더 효율적인 방법이 있는지 확실하지 않습니다.


Linq를 사용한 예 :

var types =
  myAssembly.GetTypes()
            .Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);

foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
    if (t.GetInterface("ITheInterface") != null)
    {
        ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
        executor.PerformSomething();
    }
}

다음과 같은 것을 사용하고 필요에 맞게 조정할 수 있습니다.

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

이 코드는 몇 가지 성능 향상을 사용할 수 있지만 시작입니다.


이쪽으로 가야 할지도 몰라

foreach ( var instance in Assembly.GetExecutingAssembly().GetTypes().Where(a => a.GetConstructor(Type.EmptyTypes) != null).Select(Activator.CreateInstance).OfType<ISomething>() ) 
   instance.Execute(); 

참고 URL : https://stackoverflow.com/questions/699852/how-to-find-all-the-classes-which-implement-a-given-interface

반응형