gpt4 book ai didi

c# - ICSharpCode.Decompiler + Mono.Cecil -> 如何为单个方法生成代码?

转载 作者:太空狗 更新时间:2023-10-30 00:26:44 25 4
gpt4 key购买 nike

我能够使用 Mono.Cecil 和 ICSharpCode.Decompiler 为类型或程序集生成代码。

但是如果我尝试为单个方法生成代码,我将收到错误“对象引用未设置为对象的实例。”

你们能给我一些关于这方面的提示吗?在此先感谢您提供的所有帮助。

为程序集中的所有类型生成代码的代码:

DirectoryInfo di = new DirectoryInfo(appPath);
FileInfo[] allAssemblies = di.GetFiles("*.dll");
foreach (var assemblyFile in allAssemblies)
{
string pathToAssembly = assemblyFile.FullName;
System.Reflection.Assembly assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(pathToAssembly);
Mono.Cecil.AssemblyDefinition assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(pathToAssembly,parameters);
AstBuilder astBuilder = null;

foreach (var typeInAssembly in assemblyDefinition.MainModule.Types)
{
if (typeInAssembly.IsPublic)
{
Console.WriteLine("T:{0}", typeInAssembly.Name);
//just reset the builder to include only code for a single type
astBuilder = new AstBuilder(new ICSharpCode.Decompiler.DecompilerContext(assemblyDefinition.MainModule));
astBuilder.AddType(typeInAssembly);
StringWriter output = new StringWriter();
astBuilder.GenerateCode(new PlainTextOutput(output));
string result = output.ToString();
output.Dispose();
}
}
}

为程序集中的所有公共(public)方法生成代码的代码:

DirectoryInfo di = new DirectoryInfo(appPath);
FileInfo[] allAssemblies = di.GetFiles("*.dll");
foreach (var assemblyFile in allAssemblies)
{
string pathToAssembly = assemblyFile.FullName;
System.Reflection.Assembly assembly = System.Reflection.Assembly.ReflectionOnlyLoadFrom(pathToAssembly);
Mono.Cecil.AssemblyDefinition assemblyDefinition = Mono.Cecil.AssemblyDefinition.ReadAssembly(pathToAssembly,parameters);
AstBuilder astBuilder = null;

foreach (var typeInAssembly in assemblyDefinition.MainModule.Types)
{
if (typeInAssembly.IsPublic)
{
Console.WriteLine("T:{0}", typeInAssembly.Name);
foreach (var method in typeInAssembly.Methods)
{
//just reset the builder to include only code for a single method
astBuilder = new AstBuilder(new ICSharpCode.Decompiler.DecompilerContext(assemblyDefinition.MainModule));
astBuilder.AddMethod(method);
if (method.IsPublic && !method.IsGetter && !method.IsSetter && !method.IsConstructor)
{
Console.WriteLine("M:{0}", method.Name);
StringWriter output = new StringWriter();
astBuilder.GenerateCode(new PlainTextOutput(output));
string result = output.ToString();
output.Dispose();
}
}
}
}
}

最佳答案

我遇到了同样的问题。您应该设置 DecompilerContext 的 CurrentType 属性。将您的代码更改为

astBuilder = new AstBuilder(new ICSharpCode.Decompiler.DecompilerContext(assemblyDefinition.MainModule) { CurrentType = typeInAssembly } );

关于c# - ICSharpCode.Decompiler + Mono.Cecil -> 如何为单个方法生成代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9811448/

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