0

我正在构建一个伪代码翻译器和编译器。它通过执行几个字符串操作将伪代码转换为代码,然后使用CSharpCodeProvider该类对其进行编译,最后尝试运行它。

经过几次测试,在翻译/输出代码如下的情况下:

using System;
using System.Collections.Generic;

public class TranslatedProgram
{
    public static void ReadLine(ref int destiny)
    {
        destiny = int.Parse(Console.ReadLine());
    }
    public static void InsertInStack(ref Stack<int> originalStack, int value)
    {
        Console.WriteLine("Inserting the value " + value + " to the stack.");
        originalStack.Push(value);
        foreach (int current in originalStack)
        {
            Console.WriteLine("|" + current);
        }
        Console.WriteLine("_______");
    }
    public static void Main()
    {
        int value = new int();
        Stack<int> data = new Stack<int>();
        ReadLine(ref value);
        InsertInStack(ref data, value);
    }
}

当应用程序将此代码发送到 CSharpCodeProvider 时,它不会编译。在 compilerResults 中,我收到以下错误:“找不到类型或命名空间名称 'Stack'(您是否缺少 using 指令或程序集引用?)” (CS0246)

但是,当我将这段代码原封不动地放在 VS IDE 的一个新项目中时,它运行良好。

有什么猜测吗?

谢谢。

编辑:

我通过执行以下操作从 VB 调用 CSharpCodeProvider 编译器:

Private Sub CompileButton_Click(sender As Object, e As EventArgs) Handles CompileButton.Click
        If ApplicationSaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim Compiler As New Microsoft.CSharp.CSharpCodeProvider
            Dim Results As System.CodeDom.Compiler.CompilerResults
            Results = Compiler.CompileAssemblyFromSource(New CodeDom.Compiler.CompilerParameters With {.GenerateExecutable = True, .OutputAssembly = ApplicationSaveFileDialog.FileName}, CodeTextBox.Text)
            If Results.Errors.Count = 0 Then
                Shell(ApplicationSaveFileDialog.FileName)
            Else
                For Each Exception As System.CodeDom.Compiler.CompilerError In Results.Errors
                    ExceptionsTextBox.AppendText(Exception.ErrorText)
                Next
            End If
        End If
    End Sub

如何包含对 System.dll 的引用?

4

1 回答 1

5

确保在编译时,您有对包含 .dll 的 dll 的引用Stack<>,即System.dll.

ReferencedAssemblies您可以使用类的属性添加引用CompilerParameters

CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults cr = provider.CompileAssemblyFromFile(cp, "MyFile.cs");
于 2013-05-19T23:16:48.953 回答