-2

我在 CodeDom 上玩了一会儿,收到一条错误消息。错误信息是

} 预期的!

我尝试搜索错误,但找不到任何有价值的东西。为什么我会收到此错误?

String InputCode = String.Empty;
InputCode = "MessageBox.Show((1 + 2 + 3).ToString());";

System.CodeDom.Compiler.CodeDomProvider CodeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");

System.CodeDom.Compiler.CompilerParameters CompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
CompilerParameters.ReferencedAssemblies.Add("System.dll");
CompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CompilerParameters.CompilerOptions += "/target:winexe" + " " + "/win32icon:" + "\"" + textBox6.Text + "\"";
CompilerParameters.GenerateInMemory = true;

StringBuilder Temp = new StringBuilder();
Temp.AppendLine(@"using System;");
Temp.AppendLine(@"using System.Windows.Forms;");
Temp.AppendLine(@"namespace RunTimeCompiler{");
Temp.AppendLine(@"public class Test{");
Temp.AppendLine(@"public static void Main(){");
Temp.AppendLine(@"public void Ergebnis(){");

Temp.AppendLine(InputCode);
Temp.AppendLine(@"}}}}}");

System.CodeDom.Compiler.CompilerResults CompilerResults = CodeDomProvider.CompileAssemblyFromSource(CompilerParameters, Temp.ToString());
//Auf CompilerFehler prüfen
if (CompilerResults.Errors.Count > 0)
{
    MessageBox.Show(CompilerResults.Errors[0].ErrorText, "Fehler bei Laufzeitkompilierung", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}
4

2 回答 2

3

您的代码不正确。您在另一个方法中有一个方法,这是不允许的。因此,编译器声明它需要一个}, 在public void Ergebnis().

如果你写出来你的代码是

1. using System;
2. using System.Windows.Forms;
3. namespace RunTimeCompiler {
4. public class Test {
5.     public static void Main() {
6.        public void Ergebnis() {
7.            MessageBox.Show((1 + 2 + 3).ToString());
8.        }
9.     }
10.}
11.}
12.}

请注意,在第 6 行,您需要在声明下一个方法之前关闭 Main 的方法范围。一个正确的程序是

using System;
using System.Windows.Forms;
namespace RunTimeCompiler {
public class Test {
    public static void Main() {
        new Test().Ergebnis();
    }
    public void Ergebnis() {
        MessageBox.Show((1 + 2 + 3).ToString());
    }
}
}
于 2013-06-15T16:47:26.530 回答
-1

在您粘贴的代码的最后,您的 if 语句缺少一个右大括号,而且下面的行似乎还有一个额外}的内容:

Temp.AppendLine(@"}}}}}");

看起来应该是:

Temp.AppendLine(@"}}}}");
于 2013-06-15T16:46:19.897 回答