2012-06-04 3 views
2

CodeDom 컴파일러를 사용하여 코드를 만드는 앱이 있습니다. 생성 된 어셈블리가 메모리에 있음을 알 수 있습니다. 하지만 Type.GetType (typeName)을 호출하면 null을 반환합니다. 나는 이것을 조금 혼란스럽게 느낀다.Type.GetType (string)은 동적으로 생성되는 유형을 인식해야합니까?

내가 뭘 잘못하고 있니?

static void Main(string[] args) 
{ 
    // FYI: Code is some dummy class with only 1 instance method. 
    string code = System.IO.File.ReadAllText("CodeToCompile.cs.txt"); 

    string errors = null; 
    Assembly asm = DynamicCompiler.Compile(code, generateInMemory: true, generateDebugInfo: false, message: ref errors); 

    // Get type from the generated assembly. We know there is only one. 
    Type oneAndOnlyTypeInAssembly = asm.GetTypes().First(); 

    string typeName = oneAndOnlyTypeInAssembly.AssemblyQualifiedName; 

    // Tell the type system to return instance of type based on fully qualified name. 
    // I'd expect this to work, since the assembly is already loaded to memory. 
    Type sameType = Type.GetType(typeName); 

    if (sameType != null) 
    { 
     Console.WriteLine("Type found and equal={0}", oneAndOnlyTypeInAssembly.Equals(sameType)); 
    } 
    else 
    { 
     Console.WriteLine("Type NOT FOUND"); 
    } 
} 
+0

DynamicCompiler.Compile은 CodeDom의 CSharpCodeProvider.CompileAssemblyFromSource를 래핑하는 단순한 도우미 메서드입니다. 나는 간결함을 위해 그것을 버렸다. –

답변

10

MSDN의 비고 섹션을 참조하십시오. 원하는 작업이 지원되지 않습니다.

GetType은 디스크에서로드 된 어셈블리에서만 작동합니다. GetType을 호출하여 System.Reflection.Emit 서비스를 사용하여 정의 된 동적 어셈블리에 정의 된 형식을 조회하면 일관성없는 동작이 발생할 수 있습니다. 동작은 동적 어셈블리가 지속적인지, 즉 System.Reflection.Emit.AssemblyBuilderAccess 열거 형의 RunAndSave 또는 Save 액세스 모드를 사용하여 생성되는지 여부에 따라 다릅니다. 동적 어셈블리가 영구적이며 GetType이 호출되기 전에 디스크에 기록 된 경우 로더는 디스크에 저장된 어셈블리를 찾고 해당 어셈블리를로드하고 해당 어셈블리에서 형식을 검색합니다. GetType이 호출 될 때 어셈블리가 디스크에 저장되지 않은 경우이 메서드는 null을 반환합니다. GetType은 일시적인 동적 어셈블리를 인식하지 못합니다. 따라서 GetType을 호출하여 임시 동적 어셈블리에서 형식을 검색하면 null이 반환됩니다.

+0

'Assmbly.GetTypes(). First (t => condition);'를 사용하여 가능한 한 가지 가능한 해결책이 샘플에 있습니다. –

관련 문제