programing

모든 어셈블리에서 유형 찾기

minimums 2023. 6. 22. 21:40
반응형

모든 어셈블리에서 유형 찾기

웹 사이트나 윈도우 앱에서 모든 어셈블리에서 특정 유형을 찾아야 하는데, 이를 위한 쉬운 방법이 있나요?ASP.NET MVC의 컨트롤러 팩토리가 컨트롤러에 대한 모든 어셈블리를 보는 것과 같습니다.

감사해요.

이를 위해 두 가지 단계가 있습니다.

  • AppDomain.CurrentDomain.GetAssemblies()현재 응용 프로그램 도메인에 로드된 모든 어셈블리를 제공합니다.
  • Assembly클래스는 a를 제공합니다.GetTypes()특정 어셈블리 내의 모든 형식을 검색하는 메서드입니다.

따라서 코드는 다음과 같습니다.

foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
    foreach (Type t in a.GetTypes())
    {
        // ... do something with 't' ...
    }
}

특정 유형(예: 지정된 인터페이스 구현, 공통 조상에서 상속받거나 기타)을 찾으려면 결과를 필터링해야 합니다.응용프로그램의 여러 위치에서 이 작업을 수행해야 하는 경우 다양한 옵션을 제공하는 도우미 클래스를 구축하는 것이 좋습니다.예를 들어 네임스페이스 접두사 필터, 인터페이스 구현 필터 및 상속 필터를 일반적으로 적용했습니다.

자세한 설명서는 여기와 여기에서 MSDN을 살펴보십시오.

어셈블리가 동적인지 확인하는 LINQ 솔루션:

/// <summary>
/// Looks in all loaded assemblies for the given type.
/// </summary>
/// <param name="fullName">
/// The full name of the type.
/// </param>
/// <returns>
/// The <see cref="Type"/> found; null if not found.
/// </returns>
private static Type FindType(string fullName)
{
    return
        AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => !a.IsDynamic)
            .SelectMany(a => a.GetTypes())
            .FirstOrDefault(t => t.FullName.Equals(fullName));
}

Linq를 사용하면 쉽습니다.

IEnumerable<Type> types =
            from a in AppDomain.CurrentDomain.GetAssemblies()
            from t in a.GetTypes()
            select t;

foreach(Type t in types)
{
    ...
}

일반적으로 외부에서 볼 수 있는 어셈블리에만 관심이 있습니다.따라서 GetExport를 호출해야 합니다.유형() 그러나 ReflectionTypeLoadException은 느려질 수 있습니다.다음 코드는 이러한 상황을 해결합니다.

public static IEnumerable<Type> FindTypes(Func<Type, bool> predicate)
{
    if (predicate == null)
        throw new ArgumentNullException(nameof(predicate));

    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
    {
        if (!assembly.IsDynamic)
        {
            Type[] exportedTypes = null;
            try
            {
                exportedTypes = assembly.GetExportedTypes();
            }
            catch (ReflectionTypeLoadException e)
            {
                exportedTypes = e.Types;
            }

            if (exportedTypes != null)
            {
                foreach (var type in exportedTypes)
                {
                    if (predicate(type))
                        yield return type;
                }
            }
        }
    }
}

언급URL : https://stackoverflow.com/questions/4692340/find-types-in-all-assemblies

반응형