sách gpt4 ai đã đi

Chạy mã C# động từ một chuỗi trong ngữ cảnh của biểu mẫu hiện tại (mã)

In lại 作者:行者123 更新时间:2023-11-30 15:15:59 34 4
mua khóa gpt4 Nike

我需要在当前表单(代码)的上下文中运行文本文件中的代码。其中一项要求是让代码创建新控件并将其添加到当前窗体。

例如,在Form1.csở giữa:

using System.Windows.Forms;
...

public int[] someCoords = { 20, 10 };
public string someImportantString = "Hello";

public void SayHello() {
MessageBox.Show("Hello world.");
}

private void runCodeInForm() {
// theCode will be read from a text file
string theCode = @"
// Has System.Windows.Forms already added in form
Button newButton = new Button();
newButton.Text = someImportantString; // Hello
newButton.Location = new Point(someCoords[0], someCoords[1]); // 20, 10

// Add this button to the current form
this.Controls.Add(newButton);

this.SayHello(); // Says hello. Just an example function.
";

// Execute theCode in the current form
CodeRunner.Execute(theCode, this);
}

我试过使用CSharpCodeProvider,但似乎只能将代码编译为一个单独的程序。

我喜欢这个是因为我希望用户能够将此代码(文本文件)更改为他们想要的内容。它不仅专门用于创建控件,而且还需要该功能。

我不担心程序的安全性。

1 Câu trả lời

考虑以下几点来解决问题:

  • 您应该将动态代码创建为 dll 中的类。
  • 你的类应该实现一个特定的接口(interface)或者有一个已知的方法,比如Run。因此您可以稍后在代码编译时调用该方法。
  • 您的类或已知方法应该接受一些参数来接收上下文变量。这些上下文变量可以包含一个 Form 作为参数。您还可以将上下文参数封装在类/接口(interface)中,或者为了保持简单,您可以依赖 dynamic 来传递参数。

然后运行动态代码,首先编译它,然后将上下文参数传递给类或已知方法并调用已知方法。

Ví dụ

这里是一个快速而粗略的示例,说明如何在运行时编译和运行代码并让代码使用您的上下文:

public string SomePublicField = "Hello!";
private void button1_Click(object sender, EventArgs e) {
var csc = new CSharpCodeProvider();
var parameters = new CompilerParameters(new[] {
"mscorlib.dll",
"System.Windows.Forms.dll",
"System.dll",
"System.Drawing.dll",
"System.Core.dll",
"Microsoft.CSharp.dll"});
var results = csc.CompileAssemblyFromSource(parameters,
@"
using System.Windows.Forms;
using System.Drawing;
public class Sample
{
public void DoSomething (dynamic form)
{
var b = new Button();
b.Text = form.Text;
b.Click += (s,e)=>{MessageBox.Show(form.SomePublicField);};
form.Controls.Add(b);
}
}");
//Check if compilation is successful, run the code
if (!results.Errors.HasErrors) {
var t = results.CompiledAssembly.GetType("Sample");
dynamic o = Activator.CreateInstance(t);
o.DoSomething(this);
}
else {
var errors = string.Join(Environment.NewLine,
results.Errors.Cast().Select(x => x.ErrorText));
MessageBox.Show(errors);
}
}

关于c# - 在当前表单(代码)的上下文中从字符串动态运行 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902184/

34 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com