WinForms アプリケーションのメイン フォームの TextBox の値を変更するために、テキスト ファイルのコードをコンパイルしようとしています。すなわち。メソッドを持つ別の部分クラスを呼び出しフォームに追加します。フォームには 1 つのボタン (button1) と 1 つの TextBox (textBox1) があります。
テキスト ファイル内のコードは次のとおりです。
this.textBox1.Text = "Hello World!!";
そしてコード:
namespace WinFormCodeCompile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Load code from file
StreamReader sReader = new StreamReader(@"Code.txt");
string input = sReader.ReadToEnd();
sReader.Close();
// Code literal
string code =
@"using System;
using System.Windows.Forms;
namespace WinFormCodeCompile
{
public partial class Form1 : Form
{
public void UpdateText()
{" + input + @"
}
}
}";
// Compile code
CSharpCodeProvider cProv = new CSharpCodeProvider();
CompilerParameters cParams = new CompilerParameters();
cParams.ReferencedAssemblies.Add("mscorlib.dll");
cParams.ReferencedAssemblies.Add("System.dll");
cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
cParams.GenerateExecutable = false;
cParams.GenerateInMemory = true;
CompilerResults cResults = cProv.CompileAssemblyFromSource(cParams, code);
// Check for errors
if (cResults.Errors.Count != 0)
{
foreach (var er in cResults.Errors)
{
MessageBox.Show(er.ToString());
}
}
else
{
// Attempt to execute method.
object obj = cResults.CompiledAssembly.CreateInstance("WinFormCodeCompile.Form1");
Type t = obj.GetType();
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, null);
}
}
}
}
コードをコンパイルすると、CompilerResults は WinFormCodeCompile.Form1 に textBox1 の定義が含まれていないというエラーを返します。
呼び出し元のアセンブリに対して別の部分クラス ファイルを動的に作成し、そのコードを実行する方法はありますか?
ここで本当に単純なものが欠けていると思います。