【发布时间】:2018-05-01 06:15:03
【问题描述】:
我正在开发一个可以即时编译和调试 C# 代码的应用程序。
下面包含代码的简化版本。
这段代码应该做些什么来逐步运行生成的方法并在每一步之后获取变量x和y的状态?
如果一切都应该改变就好了,我很高兴有任何建设性的回应。
编辑:澄清一下:我想做的是让我的代码调试使用反射生成的代码,而不是 Visual Studio 中的调试功能。
string code =
@"
namespace MyNameSpace
{
public class MyClass
{
public static int MyMethod()
{
var x = 3;
var y = 4;
return x * y;
}
}
}";
string namespaceName = "MyNameSpace";
string className = "MyClass";
string methodName = "MyMethod";
string language = "csharp";
string classFullname = namespaceName + "." + className;
CodeDomProvider provider = CodeDomProvider.CreateProvider(language);
CompilerParameters parameters = new CompilerParameters();
CompilerResults results;
parameters.OutputAssembly = "Compiler";
parameters.CompilerOptions = "/t:library";
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = true;
results = provider.CompileAssemblyFromSource(parameters, code);
if (results.Errors.Count != 0)
{
throw new Exception("Code compilation errors occurred.");
}
var instance = results.CompiledAssembly.CreateInstance(classFullname, false);
// TODO run the method step by step and get the state after each step
【问题讨论】:
-
“和调试 C# 代码” - 我会说这非常困难和广泛。
-
在你生成的代码中加入一个
Debugger.Break();call,看看它是否被命中,你可以从那里更进一步吗? -
好像是this question的副本。
-
我认为这是不可能的。调试器是一个独立的进程,它通过操作系统服务与被调试者通信。调试对象必须使用指向原始源的调试信息进行编译,并生成适当的 pdb 伴侣。也许您正在寻求解释 C# 代码?
-
@MartiendeJong 这个页面 [codeguru.com/cpp/v-s/debug/debuggers/article.php/c16451/… 可以让您了解编写调试器所涉及的内容。
标签: c# reflection.emit codedom