주어진 유형의 .NET에 대한 어셈블리 (System.Reflection.Assembly)를 얻는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1141121

문제

.NET에서 유형 이름이 주어지면 유형의 조립 (System.Reflection.Assembly)에 해당 유형이 정의되는지 알려주는 메소드가 있습니까?

내 프로젝트에는 이미 그 어셈블리에 대한 참조가 있다고 가정합니다.

도움이 되었습니까?

해결책

Assembly.getAsSembly 유형의 인스턴스가 있다고 가정하고 type.getType는 어셈블리 이름을 포함하는 자격을 갖춘 유형 이름을 가지고 있다고 가정합니다.

기본 유형 이름 만있는 경우 다음과 같은 작업을 수행해야합니다.

public static String GetAssemblyNameContainingType(String typeName) 
{
    foreach (Assembly currentassembly in AppDomain.CurrentDomain.GetAssemblies()) 
    {
        Type t = currentassembly.GetType(typeName, false, true);
        if (t != null) {return currentassembly.FullName;}
    }

    return "not found";
}

이것은 또한 유형이 루트에서 선언된다고 가정합니다. 이름으로 네임 스페이스 또는 동봉 유형을 제공하거나 같은 방식으로 반복해야합니다.

다른 팁

Assembly.GetAssembly(typeof(System.Int32))

바꾸다 System.Int32 필요한 유형으로. 수락하기 때문에 a Type 매개 변수, 예를 들어 다음과 같은 방식으로 수행 할 수 있습니다.

string GetAssemblyLocationOfObject(object o) {
    return Assembly.GetAssembly(o.GetType()).Location;
}

수락 된 답변을 내 자신의 목적 (어셈블리 이름 대신 어셈블리 객체를 반환)을 조정하고 vb.net 및 linq에 대한 코드를 리팩토링했습니다.

Public Function GetAssemblyForType(typeName As String) As Assembly
    Return AppDomain.CurrentDomain.GetAssemblies.FirstOrDefault(Function(a) a.GetType(typeName, False, True) IsNot Nothing)
End Function

다른 사람이 허용 된 답변에 대한 Linqy 솔루션을 원한다면 여기서 공유하고 있습니다.

Type.GetType(typeNameString).Assembly

당신이 그것을 사용할 수 있다면,이 구문은 가장 짧거나 깨끗합니다.

typeof(int).Assembly
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top