我有一个使用 CodeDom 编译器创建一些代码的应用程序。我可以看到生成的程序集在内存中。但是当我调用 Type.GetType(typeName) 时,它返回 null。我觉得这有点令人困惑。
我究竟做错了什么?
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 http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx。不支持您想做的事情:
GetType 仅适用于从磁盘加载的程序集。如果调用 GetType 来查找在使用 System.Reflection.Emit 服务定义的动态程序集中定义的类型,则可能会出现不一致的行为。该行为取决于动态程序集是否是持久的,即使用 System.Reflection.Emit.AssemblyBuilderAccess 枚举的 RunAndSave 或 Save 访问模式创建的。如果动态程序集是持久性的,并且在调用 GetType 之前已写入磁盘,则加载程序会在磁盘上查找保存的程序集,加载该程序集,并从该程序集中检索类型。如果调用 GetType 时程序集尚未保存到磁盘,则该方法返回 null。 GetType 不理解瞬态动态程序集;因此,调用 GetType 来检索瞬态动态程序集中的类型将返回 null.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)