gpt4 book ai didi

c# - 在运行时编译代码时添加额外的引用

转载 作者:行者123 更新时间:2023-12-02 00:17:42 24 4
gpt4 key购买 nike

我找到了这个程序( http://support.microsoft.com/kb/304655 ),我在运行时编译代码,它适用于使用引用的代码,

using System;

以下是在运行时编译代码的程序的代码,

        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();

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 = icc.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);
}

以下是我需要在运行时编译的代码,

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;

namespace Tsubame
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"url");

// Create Client
WebClient client = new WebClient();

// Assign Credentials
client.Credentials = new NetworkCredential("user", "pass");

//Grab Data
var data = client.DownloadString(@"url");

JObject o = JObject.Parse(data);
string getFristRow = Convert.ToString(o["Body"][0]["RowId"]);

string encaplulateStart = "\\\"";
string encaplulateEnd = "\\\":";

List<string> _matches = new List<string>();
_matches = Regex.Matches(getFristRow, @"(?<=" + encaplulateStart + ").*(?=" + encaplulateEnd + ")")
.Cast<Match>()
.Select(m => m.Value)
.ToList();

foreach (string head in _matches)
{
Console.WriteLine(head);

}
Console.ReadLine();
}
}
}

但是当我输入时给出错误代码,

    Error Number: CS0234

对于 System.out 以外的引用。请问如何在运行时添加额外的引用以便编译成功:) 非常感谢:)

最佳答案

您需要使用 CompilerParameters.ReferencedAssembliesCompilerParameters 中添加引用:

var parameters = CompilerParameters
{
GenerateExecutable = true,
OutputAssembly = Output,
ReferencedAssemblies = {
"System.dll",
"System.Core.dll",
// etc
}
};

(当然,您不必使用对象初始值设定项语法来设置它,但在我看来,它使它更简洁。)

关于c# - 在运行时编译代码时添加额外的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12488782/

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