gpt4 book ai didi

c# - CSharpCodeProvider在System.Collections.Generic下看不到Stack

转载 作者:行者123 更新时间:2023-12-02 10:49:27 25 4
gpt4 key购买 nike

我正在构建一个伪代码转换器和编译器。
它通过执行几个字符串操作将伪代码转换为代码,然后使用 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时,它不会编译。在compileResults中,出现以下错误:“找不到类型或 namespace 名称'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的引用?

最佳答案

确保在编译时,对包含Stack<>的dllt的dll进行引用。

您可以使用System.dll类的ReferencedAssemblies属性添加引用:

CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults cr = provider.CompileAssemblyFromFile(cp, "MyFile.cs");

关于c# - CSharpCodeProvider在System.Collections.Generic下看不到Stack <T>类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16640424/

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