使用我动态编译的表单中的程序 class
Use program class from my dynamically compiled form
我有一个 class Read/Write 来自注册表。但是我如何从动态编译的表单中使用这个 class 。我可以执行函数,甚至可以从动态编译的表单中获取 var values,但是如何执行我的程序函数或从我的动态编译的表单中获取 var values。
注册表助手class
using Microsoft.Win32;
namespace myForm
{
class RegistryHelper
{
public void WriteKey(string k, string value)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey("rGO");
key.SetValue(k, value);
key.Close();
}
public string ReadKey(string k)
{
RegistryKey op = Registry.CurrentUser.OpenSubKey("rGO");
return (string)op.GetValue(k);
}
}
}
我在 Form1 中执行测试函数的示例 class
using System;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;
namespace myForm
{
class Program
{
static void Main(string[] args)
{
using (var foo = new CSharpCodeProvider())
{
var parameters = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false
};
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
var source = File.ReadAllText("form.txt");
CompilerResults results = foo.CompileAssemblyFromSource(parameters, source);
Type type = results.CompiledAssembly.GetType("myForm.Form1");
object compiledObject = Activator.CreateInstance(type);
// Execure test function from dynamically compiled form
type.GetMethod("test").Invoke(compiledObject, new object[] { });
}
}
}
}
form.txt 来源
using System.Windows.Forms;
namespace myForm
{
public partial class Form1 : Form
{
public static int _testVar = 0; // how can i get this var value?
public Form1()
{
InitializeComponent();
}
public void test()
{
MessageBox.Show("test");
}
}
}
namespace myForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 12);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(260, 204);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 222);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(260, 40);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 274);
this.Controls.Add(this.button1);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button button1;
}
}
为此,您只需要在引用编译代码中添加对自身的引用:
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace ConsoleApplication212
{
class Program
{
static void Main(string[] args)
{
//dynamic code
var source = @"
static class Program
{
public static void Start()
{
//We call the Test method of the class Console Application 212.Helper
ConsoleApplication212.Helper.Test();
}
}";
//compile and run
Run(source);
Console.ReadLine();
}
static void Run(string source)
{
using (var provider = new CSharpCodeProvider())
{
var parameters = new CompilerParameters { GenerateInMemory = true };
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
//link your self
parameters.ReferencedAssemblies.Add(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase));
//compile
var result = provider.CompileAssemblyFromSource(parameters, source);
if (result.Errors.Count > 0)
throw new Exception(result.Errors[0].ErrorText);
//Find class Program
var type = result.CompiledAssembly.GetType("Program");
//вызыаем метод Start
type.GetMethod("Start").Invoke(null, null);
}
}
}
/// <summary>
/// Public class that will be used in dynamically compiled code
/// </summary>
public static class Helper
{
public static void Test()
{
MessageBox.Show("Hi from Helper");
}
}
}
我有一个 class Read/Write 来自注册表。但是我如何从动态编译的表单中使用这个 class 。我可以执行函数,甚至可以从动态编译的表单中获取 var values,但是如何执行我的程序函数或从我的动态编译的表单中获取 var values。
注册表助手class
using Microsoft.Win32;
namespace myForm
{
class RegistryHelper
{
public void WriteKey(string k, string value)
{
RegistryKey key = Registry.CurrentUser.CreateSubKey("rGO");
key.SetValue(k, value);
key.Close();
}
public string ReadKey(string k)
{
RegistryKey op = Registry.CurrentUser.OpenSubKey("rGO");
return (string)op.GetValue(k);
}
}
}
我在 Form1 中执行测试函数的示例 class
using System;
using System.CodeDom.Compiler;
using System.IO;
using Microsoft.CSharp;
namespace myForm
{
class Program
{
static void Main(string[] args)
{
using (var foo = new CSharpCodeProvider())
{
var parameters = new CompilerParameters
{
GenerateInMemory = true,
GenerateExecutable = false
};
parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");
parameters.ReferencedAssemblies.Add("System.Drawing.dll");
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
var source = File.ReadAllText("form.txt");
CompilerResults results = foo.CompileAssemblyFromSource(parameters, source);
Type type = results.CompiledAssembly.GetType("myForm.Form1");
object compiledObject = Activator.CreateInstance(type);
// Execure test function from dynamically compiled form
type.GetMethod("test").Invoke(compiledObject, new object[] { });
}
}
}
}
form.txt 来源
using System.Windows.Forms;
namespace myForm
{
public partial class Form1 : Form
{
public static int _testVar = 0; // how can i get this var value?
public Form1()
{
InitializeComponent();
}
public void test()
{
MessageBox.Show("test");
}
}
}
namespace myForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 12);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(260, 204);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(12, 222);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(260, 40);
this.button1.TabIndex = 1;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 274);
this.Controls.Add(this.button1);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.Button button1;
}
}
为此,您只需要在引用编译代码中添加对自身的引用:
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace ConsoleApplication212
{
class Program
{
static void Main(string[] args)
{
//dynamic code
var source = @"
static class Program
{
public static void Start()
{
//We call the Test method of the class Console Application 212.Helper
ConsoleApplication212.Helper.Test();
}
}";
//compile and run
Run(source);
Console.ReadLine();
}
static void Run(string source)
{
using (var provider = new CSharpCodeProvider())
{
var parameters = new CompilerParameters { GenerateInMemory = true };
parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
//link your self
parameters.ReferencedAssemblies.Add(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase));
//compile
var result = provider.CompileAssemblyFromSource(parameters, source);
if (result.Errors.Count > 0)
throw new Exception(result.Errors[0].ErrorText);
//Find class Program
var type = result.CompiledAssembly.GetType("Program");
//вызыаем метод Start
type.GetMethod("Start").Invoke(null, null);
}
}
}
/// <summary>
/// Public class that will be used in dynamically compiled code
/// </summary>
public static class Helper
{
public static void Test()
{
MessageBox.Show("Hi from Helper");
}
}
}