我正在为学生制作一个 Silverlight 应用程序,我正在寻找一个关键组件。在应用程序中,学生应该能够在文本框中添加 C# 代码(一节课)。我想做的是:验证代码是有效的 C# 并且理想情况下还确保它正确实现给定的接口(interface)。那里有可以帮助我解决这个问题的控件吗?
克里斯
最佳答案
示例代码基于 CodecomProvider :
private void button1_Click(object sender, System.EventArgs e)
{
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
//Make sure we generate an EXE, not a DLL
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
textBox2.ForeColor = Color.Red;
foreach (CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}
}
Add the beginning of the file, add these using statements:
using System.CodeDom.Compiler;
using System.Diagnostics;
关于Silverlight GUI 中的 C# 代码验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11139018/