在当前形式(代码)的上下文中从字符串动态运行C#代码
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在当前形式(代码)的上下文中从字符串动态运行C#代码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2387字,纯文字阅读大概需要4分钟。
内容图文
![在当前形式(代码)的上下文中从字符串动态运行C#代码](/upload/InfoBanner/zyjiaocheng/686/6f9dbc04db2e41fc81830766dc76d4a6.jpg)
我需要在当前表单(代码)的上下文中从文本文件运行代码.要求之一是让代码创建并向当前表单添加新控件.
例如,在Form1.cs中:
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,但似乎只能将代码编译为单独的程序.
我想要这样做是因为我希望用户能够将此代码(文本文件)更改为他们想要的.它不仅专门用于创建控件,而且还需要该功能.
我不担心程序的安全性.
解决方法:
请考虑以下几点来解决问题:
>您应该将动态代码创建为dll中的类.
>您的类应实现特定的接口或具有诸如Run之类的已知方法.因此,您可以稍后在代码编译时调用该方法.
>您的类或已知方法应接受一些参数来接收上下文变量.这些上下文变量可以包含Form作为参数.您还可以将上下文参数封装在类/接口中,或者为了使其简单起见,可以依靠动态传递参数.
然后,要运行动态代码,请先对其进行编译,然后将上下文参数传递给该类或已知方法,然后调用该已知方法.
例
这是一个简单又肮脏的示例,说明如何在运行时编译和运行代码,并让代码使用您的上下文:
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<CompilerError>().Select(x => x.ErrorText));
MessageBox.Show(errors);
}
}
内容总结
以上是互联网集市为您收集整理的在当前形式(代码)的上下文中从字符串动态运行C#代码全部内容,希望文章能够帮你解决在当前形式(代码)的上下文中从字符串动态运行C#代码所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。