c#动态编译执行对象方法示例 运用映射机制创建对象

C#是一种编译型的语言,程序执行,首先要经过编译器编译,如何让C#像一种脚本一样,在要执行的时候,进行编译,这里,我们可以用Microsoft.CSharp空间下的CSharpCodeProvider提供类,来达到动态编译的效果。在这里,我新建一个控制台程序,在Program.cs类里引用using System.CodeDom.Compiler;
using System.Reflection;using Microsoft.CSharp;三大命名空间

复制代码 代码如下:

#region using directiry
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
#endregion
/*==============================================================================
 *
 * author:[email protected]
 * link:http://my.oschina.net/lichaoqiang
 *
 *
 * ============================================================================*/
namespace CodeDom
{
    class Program
    {
        #region 主程序入口
        ///
        ///主程序入口
        ///

        ///
        static void Main(string[] args)
        {
            //1>实例化C#代码服务提供对象
            CSharpCodeProvider provider = new CSharpCodeProvider();
            //2>声明编译器参数
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            try
            {
                //3>动态编译
                CompilerResults result = provider.CompileAssemblyFromSource(parameters, BuildCSharpCode());
                if (result.Errors.Count > 0)
                {
                    Console.Write("编译出错!");
                }
                //4>如果编译没有出错,此刻已经生成动态程序集LCQ.LCQClass
                //5>开始玩C#映射
                Assembly assembly = result.CompiledAssembly;
                object obj = assembly.CreateInstance("LCQ.LCQClass");
                Type type = assembly.GetType("LCQ.LCQClass");
                //6>获取对象方法
                MethodInfo method = type.GetMethod("Sum");
                object[] objParameters = new object[2] { 1, 5 };
                int iResult = Convert.ToInt32(method.Invoke(obj, objParameters));//唤醒对象,执行行为
                Console.Write(iResult);
                Console.Read();
            }
            catch (System.NotImplementedException ex)
            {
                Console.Write(ex.Message);
            }
            catch (System.ArgumentException ex)
            {
                Console.Write(ex.Message);
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
        #endregion

        #region 生成代码块
        ///


        /// 生成代码块
        ///

        ///
        private static string BuildCSharpCode()
        {
            string fileName = AppDomain.CurrentDomain.BaseDirectory.Replace("Debug", string.Empty).Replace("Release", string.Empty) + "CodeFile.cs";
            string strCodeDom = File.ReadAllText(fileName);
            return strCodeDom;
        }
        #endregion
    }
}

你可能感兴趣的:(c#动态编译执行对象方法示例 运用映射机制创建对象)