Should Type.GetType(string) be aware of dynamicall

2019-05-24 16:53发布

问题:

I have an app which creates some code using CodeDom compiler. I can see that the generated assembly is in memory. But when I call Type.GetType(typeName), it returns null. I find this a little bit confusing.

What am I doing wrong?

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

回答1:

Please see the remarks section in MSDN. What you want to do is not supported:

GetType only works on assemblies loaded from disk. If you call GetType to look up a type defined in a dynamic assembly defined using the System.Reflection.Emit services, you might get inconsistent behavior. The behavior depends on whether the dynamic assembly is persistent, that is, created using the RunAndSave or Save access modes of the System.Reflection.Emit.AssemblyBuilderAccess enumeration. If the dynamic assembly is persistent and has been written to disk before GetType is called, the loader finds the saved assembly on disk, loads that assembly, and retrieves the type from that assembly. If the assembly has not been saved to disk when GetType is called, the method returns null. GetType does not understand transient dynamic assemblies; therefore, calling GetType to retrieve a type in a transient dynamic assembly returns null.