Nah*_*eto 0 .net c# compiler-errors pseudocode csharpcodeprovider
我正在构建一个伪代码转换器和编译器.它通过执行几个字符串操作将伪代码转换为代码,然后它使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
当应用程序将此代码发送到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
Run Code Online (Sandbox Code Playgroud)
我怎么能包含对System.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");
Run Code Online (Sandbox Code Playgroud)