0

我设法创建了一个动态创建的字符串以编译为代码,它执行 MessageBox.Show 等基本内容或创建整数、字符串等。现在我想从我生成的代码中打开一个实例,我该如何实现那?我使用从网上找到的代码开始,如下所述。问候。

               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);
            }
4

0 回答 0