使用我动态编译的表单中的程序类

时间:2016-05-10 17:45:44

标签: c# dynamic compilation dynamically-generated compiled

我有一个从注册表读/写的类。但是我如何从动态编译的表单中使用这个类。我可以执行函数,甚至可以从动态编译的表单中获取var的值,但是我如何执行我的程序函数或从动态编译的表单中获取var值。

RegistryHelper类

\/\*.*\*\/

我在Form1类中执行测试函数的示例

SELECT job_id,SUM(numerical value) 
FROM table_name 
group by job_id

form.txt来源

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

1 个答案:

答案 0 :(得分:0)

要做到这一点,您只需要在参考编译代码中添加对自身的引用

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