gpt4 book ai didi

c# - 如何在使用 CodeDom 编译之前检查编译错误

转载 作者:行者123 更新时间:2023-11-30 16:27:31 25 4
gpt4 key购买 nike

我使用 CodeDom 允许自定义脚本 (C#) 在我创建的应用程序中运行。在编写脚本时,我希望能够检查编译错误。代码在很晚的时间被添加并编译到内存中并运行,所以我不希望在编写脚本时编译的程序集保留在内存中。

实现此目标的最佳方法是什么?

是否可以在编译后从内存中删除程序集?

private void Item_Click(object sender, EventArgs e)
{
List<string> assemblyNames = new List<string> { };
List<string> code = new List<string> { };
foreach (string str in GetCompileParameters())
if (!assemblyNames.Contains(str))
assemblyNames.Add(str);
code.AddRange(GetScriptCode());

CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
CompilerParameters mCompileParams = new CompilerParameters(assemblyNames.ToArray());
mCompileParams.GenerateInMemory = true;
mCompileParams.CompilerOptions = "/target:library /optimize";

CompilerResults results = provider.CompileAssemblyFromSource(mCompileParams, code.ToArray());
if (results.Errors.HasErrors)
{
string error = "The following compile error occured:\r\n";
foreach (CompilerError err in results.Errors)
error += "File: " + err.FileName + "; Line (" + err.Line + ") - " + err.ErrorText + "\n";
MessageBox.Show(error);
return;
}
MessageBox.Show("No errors found");

//Need to Remove assembly here
}

更新:

谢谢基思。

对于任何感兴趣的人,这是我在 Roslyn 中使用的新代码

using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

...

private void Item_Click(object sender, EventArgs e)
{
List<string> assemblyNames = new List<string> { };
foreach (string str in GetCompileParameters())
if (!assemblyNames.Contains(str))
assemblyNames.Add(str);

SyntaxTree tree = SyntaxTree.ParseCompilationUnit(mScenario.GetScriptCode("ScriptName"));
Compilation com = Compilation.Create("Script");
com = com.AddReferences(new AssemblyFileReference(typeof(Object).Assembly.Location)); // Add reference mscorlib.dll
com = com.AddReferences(new AssemblyFileReference(typeof(System.Linq.Enumerable).Assembly.Location)); // Add reference System.Core.dll
com = com.AddReferences(new AssemblyFileReference(typeof(System.Net.Cookie).Assembly.Location)); // Add reference System.dll
foreach (string str in assemblyNames)
com = com.AddReferences(new AssemblyFileReference(str)); // Add additional references
com = com.AddSyntaxTrees(tree);

Diagnostic[] dg = com.GetDiagnostics().ToArray();
if (dg.Length > 0)
{
string error = "The following compile error occured:\r\n";
foreach (Diagnostic d in dg)
error += "Info: " + d.Info + "\n";
MessageBox.Show(error, "Compile Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
} else {
MessageBox.Show("No errors found.", "Code Compiler", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

最佳答案

您可以使用新发布的http://msdn.microsoft.com/en-us/roslyn

关于c# - 如何在使用 CodeDom 编译之前检查编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7830640/

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