Fil*_*ącz 2 .net c# reflection codedom
我有一个应用程序,使用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");
}
}
Run Code Online (Sandbox Code Playgroud)
Dir*_*mar 10
请参阅MSDN中的备注部分.不支持您想要做的事情:
GetType仅适用于从磁盘加载的程序集.如果调用GetType来查找使用System.Reflection.Emit服务定义的动态程序集中定义的类型,则可能会出现不一致的行为.行为取决于动态程序集是否持久,即使用System.Reflection.Emit.AssemblyBuilderAccess枚举的RunAndSave或Save访问模式创建.如果动态程序集是持久的并且在调用GetType之前已写入磁盘,则加载程序会在磁盘上查找已保存的程序集,加载该程序集,并从该程序集中检索该类型.如果在调用GetType时尚未将程序集保存到磁盘,则该方法返回null.GetType不了解瞬态动态组件; 因此,调用GetType以检索瞬态动态程序集中的类型将返回null.
| 归档时间: |
|
| 查看次数: |
900 次 |
| 最近记录: |