3

我正在尝试在文本文件中编译代码以更改 WinForms 应用程序主窗体上的 TextBox 中的值。IE。向调用表单添加另一个带有方法的部分类。该表单有一个按钮 (button1) 和一个 TextBox (textBox1)。

文本文件中的代码是:

this.textBox1.Text = "你好世界!!";

和代码:

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 的定义。

有没有办法为调用程序集动态创建另一个部分类文件并执行该代码?

我想我在这里遗漏了一些非常简单的东西。

4

2 回答 2

5

Partial classes can't span assemblies - assembly is the unit of compilation, and partial classes become a single class once compiled (there's no equivalent concept on CLR level).

于 2010-04-24T06:22:09.690 回答
1

You could try using parameters to pass the object you want to manipulate, like:

// etc
public void UpdateText(object passBox)
{" + input + @" }
// more etc
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, new object[] { this.textbox });

So that way the snippet would result as:

(passBox as TextBox).Text = "Hello World!!";
于 2010-04-24T06:38:06.313 回答