2009-03-03 4 views
6

문자열을 .NET의 Type 개체로 변환하는 가장 좋은 방법은 무엇입니까?.NET의 문자열에서 Type 개체를 가져 오는 가장 좋은 방법

문제는 고려해야 할

  • 유형은 다른 어셈블리에있을 수 있습니다.
  • 형식의 어셈블리가 아직로드되지 않았을 수 있습니다.

이 내 시도,하지만 당신은이 작업을 수행하기 위해 Type.GetType(string)를 사용할 수는 두 번째 문제를

Public Function FindType(ByVal name As String) As Type 
    Dim base As Type 

    base = Reflection.Assembly.GetEntryAssembly.GetType(name, False, True) 
    If base IsNot Nothing Then Return base 

    base = Reflection.Assembly.GetExecutingAssembly.GetType(name, False, True) 
    If base IsNot Nothing Then Return base 

    For Each assembly As Reflection.Assembly In _ 
     AppDomain.CurrentDomain.GetAssemblies 
     base = assembly.GetType(name, False, True) 
     If base IsNot Nothing Then Return base 
    Next 
    Return Nothing 
End Function 
+0

두 번째 경우에 대한 설명은 어렵습니다. 언로드 된 어셈블리가 어디에 존재하는지 일반적으로 알 수있는 방법은 무엇입니까? 그렇지 않으면 [이 답변] (http://stackoverflow.com/a/7286354/661933)을 참조하십시오. – nawfal

답변

3

두 번째 GetReferencedAssemblies() 메서드를 호출해야 할 수도 있습니다.

namespace reflectme 
{ 
    using System; 
    public class hello 
    { 
     public hello() 
     { 
      Console.WriteLine("hello"); 
      Console.ReadLine(); 
     } 
     static void Main(string[] args) 
     { 
      Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType("reflectme.hello"); 
      t.GetConstructor(System.Type.EmptyTypes).Invoke(null); 
     } 
    } 
} 
9

를 해결하지 않습니다. 형식 이름은 어셈블리가 수식되어야하지만 메서드는 필요에 따라 어셈블리를로드합니다. 형식이 mscorlid이거나 GetType 호출을 실행하는 어셈블리 인 경우 어셈블리 자격이 필요하지 않습니다.

+0

형식을 찾을 수없는 경우 예외를 throw하지 않으며 null을 반환합니다. 유형이 존재할 것으로 예상되면 Type.GetType (string, bool) 오버로드를 사용하고 유형을로드 할 수없는 경우 true를 전달하는 것이 좋습니다. –

+0

"assembly qualified"는 "NLog, 버전 = 1.0.0.505, Culture = 중립, PublicKeyToken = 5120e14c03d0593c, processorArchitecture = MSIL"과 같은 전체 형식 이름을 넣어야 함을 의미합니다. –

+0

그게 많은 도움이되지 않습니다. 완전 자격을 얻은 날 제로의 기회. –

관련 문제