动态地从字符串创建代码,执行它以调用form.showdialog()方法;

时间:2012-04-06 09:44:11

标签: c# visual-studio

我已经设法创建一个动态创建的字符串来编译为代码,它完成基本的东西,如MessageBox.Show或创建整数,字符串等。现在我想从我生成的代码中打开一个from的实例,如何我可以实现吗?我使用从网上找到的代码开始,如下所述。注意。

               string lcCode = this.memoEdit1.Text;

            lcCode = @"
using System;
using System.IO;
using System.Windows.Forms;

namespace MyNamespace {
public class MyClass {

public object DynamicCode(params object[] Parameters) {
" + lcCode + 
"return (object) DateTime.Now;"+
"}   }    }";




            ICodeCompiler loCompiler = new CSharpCodeProvider().CreateCompiler();
            CompilerParameters loParameters = new CompilerParameters();

            // ref assmbles lazım ekle,mssql vs.
            loParameters.ReferencedAssemblies.Add("System.dll");
            loParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");



            loParameters.GenerateInMemory = true;

            // yuru
            CompilerResults loCompiled = loCompiler.CompileAssemblyFromSource(loParameters, lcCode);


            #region errör
            if (loCompiled.Errors.HasErrors)
            {
                string lcErrorMsg = "";

                // erörrler
                lcErrorMsg = loCompiled.Errors.Count.ToString() + " Errors:";
                for (int x = 0; x < loCompiled.Errors.Count; x++)
                    lcErrorMsg = lcErrorMsg + "\r\nLine: " + loCompiled.Errors[x].Line.ToString() + " - " +
                        loCompiled.Errors[x].ErrorText;

                MessageBox.Show(lcErrorMsg + "\r\n\r\n" + lcCode, "Erörrz", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            # endregion

            //this.memoEdit1.Text = lcCode;

            Assembly loAssembly = loCompiled.CompiledAssembly;

            // Object dinamik !!!!1!1  o yüzden obje kalsın!


            object loObject = loAssembly.CreateInstance("MyNamespace.MyClass");
            if (loObject == null)
            {
                MessageBox.Show("Class error");
                return;
            }

            object[] loCodeParms = new object[1];
            loCodeParms[0] = "Test";

            try
            {
                object loResult = loObject.GetType().InvokeMember("DynamicCode",BindingFlags.InvokeMethod, null, loObject, loCodeParms);





                //MessageBox.Show("Method Call Result:\r\n\r\n" + loResult.ToString(), "Sonuç", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception loError)
            {
                MessageBox.Show(loError.Message, "Erörrz", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

0 个答案:

没有答案