gpt4 book ai didi

c# - Type.GetType(string) 应该知道动态生成的类型吗?

转载 作者:行者123 更新时间:2023-11-30 19:18:59 24 4
gpt4 key购买 nike

我有一个使用 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中的备注部分.不支持您想执行的操作:

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.

关于c# - Type.GetType(string) 应该知道动态生成的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10887609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com