Type.GetType(string) 应该知道动态生成的类型吗? [英] Should Type.GetType(string) be aware of dynamically generated types?

查看:42
本文介绍了Type.GetType(string) 应该知道动态生成的类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它使用 CodeDom 编译器创建一些代码.我可以看到生成的程序集在内存中.但是当我调用 Type.GetType(typeName) 时,它返回 null.我觉得这有点令人困惑.

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.

我做错了什么?

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

推荐答案

请参阅<中的备注部分强>MSDN.不支持您要执行的操作:

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

GetType 仅适用于从磁盘加载的程序集.如果调用 GetType 来查找使用 System.Reflection.Emit 服务定义的动态程序集中定义的类型,则可能会出现不一致的行为.该行为取决于动态程序集是否是持久的,即使用 System.Reflection.Emit.AssemblyBuilderAccess 枚举的 RunAndSave 或 Save 访问模式创建.如果动态程序集是持久的并且在调用 GetType 之前已写入磁盘,则加载程序会在磁盘上找到保存的程序集,加载该程序集,并从该程序集中检索类型.如果在调用 GetType 时程序集尚未保存到磁盘,则该方法返回 null.GetType 不理解瞬态动态程序集;因此,调用 GetType 来检索瞬态动态程序集中的类型会返回 null.

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.

这篇关于Type.GetType(string) 应该知道动态生成的类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆