C\#동적 실행 문자열(동적 생 성 코드)의 인 스 턴 스 코드


using System;
using System.Data;
using System.Configuration;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;

namespace EvalGuy
{
    /// <summary>
    ///
    /// , !
    /// </summary>
    public class Evaluator
    {
        #region
        /// <summary>
        ///
        /// </summary>
        /// <param name="items">
        ///
        /// </param>
        public Evaluator(EvaluatorItem[] items)
        {
            ConstructEvaluator(items);        //
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="returnType"> </param>
        /// <param name="expression"> </param>
        /// <param name="name"> </param>
        public Evaluator(Type returnType, string expression, string name)
        {
            //
            EvaluatorItem[] items = { new EvaluatorItem(returnType, expression, name) };
            ConstructEvaluator(items);        //
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="item"> </param>
        public Evaluator(EvaluatorItem item)
        {
            EvaluatorItem[] items = { item };//
            ConstructEvaluator(items);        //
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="items"> </param>
        private void ConstructEvaluator(EvaluatorItem[] items)
        {
            // C#
            ICodeCompiler comp = (new CSharpCodeProvider().CreateCompiler());
            //
            CompilerParameters cp = new CompilerParameters();

            cp.ReferencedAssemblies.Add("system.dll");                // system.dll
            cp.ReferencedAssemblies.Add("system.data.dll");            // system.data.dll
            cp.ReferencedAssemblies.Add("system.xml.dll");            // system.xml.dll
            cp.GenerateExecutable = false;                            //
            cp.GenerateInMemory = true;                                //

            StringBuilder code = new StringBuilder();                //
            /*
             * 
             */
            code.Append("using System; /n");
            code.Append("using System.Data; /n");
            code.Append("using System.Data.SqlClient; /n");
            code.Append("using System.Data.OleDb; /n");
            code.Append("using System.Xml; /n");

            code.Append("namespace EvalGuy { /n");                    // EvalGuy,

            code.Append("  public class _Evaluator { /n");            // _Evaluator ,
            foreach (EvaluatorItem item in items)                //
            {
                code.AppendFormat("    public {0} {1}() ",            //
                                  item.ReturnType.Name,                //
                                  item.Name);                        //
                code.Append("{ ");                                    //
                code.AppendFormat("return ({0});", item.Expression);// ,
                code.Append("}/n");                                    //
            }
            code.Append("} }");                                    //

            //
            CompilerResults cr = comp.CompileAssemblyFromSource(cp, code.ToString());

            if (cr.Errors.HasErrors)                            //
            {
                StringBuilder error = new StringBuilder();            //
                error.Append(" : ");                //
                foreach (CompilerError err in cr.Errors)            //
                {
                    error.AppendFormat("{0}/n", err.ErrorText);        // ,
                }
                throw new Exception(" : " + error.ToString());//
            }
            Assembly a = cr.CompiledAssembly;                        //
            _Compiled = a.CreateInstance("EvalGuy._Evaluator");        // EvalGuy._Evaluator
        }
        #endregion

        #region
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"> </param>
        /// <returns> </returns>
        public int EvaluateInt(string name)
        {
            return (int)Evaluate(name);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"> </param>
        /// <returns> </returns>
        public string EvaluateString(string name)
        {
            return (string)Evaluate(name);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"> </param>
        /// <returns> </returns>
        public bool EvaluateBool(string name)
        {
            return (bool)Evaluate(name);
        }
        /// <summary>
        /// object
        /// </summary>
        /// <param name="name"> </param>
        /// <returns> </returns>
        public object Evaluate(string name)
        {
            MethodInfo mi = _Compiled.GetType().GetMethod(name);// _Compiled name
            return mi.Invoke(_Compiled, null);                    // mi
        }
        #endregion

        #region
        /// <summary>
        ///
        /// </summary>
        /// <param name="code"> </param>
        /// <returns> </returns>
        static public int EvaluateToInteger(string code)
        {
            Evaluator eval = new Evaluator(typeof(int), code, staticMethodName);// Evaluator
            return (int)eval.Evaluate(staticMethodName);                        //
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="code"> </param>
        /// <returns> </returns>
        static public string EvaluateToString(string code)
        {
            Evaluator eval = new Evaluator(typeof(string), code, staticMethodName);// Evaluator
            return (string)eval.Evaluate(staticMethodName);                        //
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="code"> </param>
        /// <returns> </returns>
        static public bool EvaluateToBool(string code)
        {
            Evaluator eval = new Evaluator(typeof(bool), code, staticMethodName);// Evaluator
            return (bool)eval.Evaluate(staticMethodName);                        //
        }
        /// <summary>
        /// object
        /// </summary>
        /// <param name="code"> </param>
        /// <returns> </returns>
        static public object EvaluateToObject(string code)
        {
            Evaluator eval = new Evaluator(typeof(object), code, staticMethodName);// Evaluator
            return eval.Evaluate(staticMethodName);                                // object
        }
        #endregion

        #region
        /// <summary>
        ///
        /// </summary>
        private const string staticMethodName = "__foo";
        /// <summary>
        /// ,
        /// </summary>
        object _Compiled = null;
        #endregion
    }
    /// <summary>
    /// ( )
    /// </summary>
    public class EvaluatorItem
    {
        /// <summary>
        ///
        /// </summary>
        public Type ReturnType;
        /// <summary>
        ///
        /// </summary>
        public string Expression;
        /// <summary>
        ///
        /// </summary>
        public string Name;
        /// <summary>
        ///
        /// </summary>
        /// <param name="returnType"> </param>
        /// <param name="expression"> </param>
        /// <param name="name"> </param>
        public EvaluatorItem(Type returnType, string expression, string name)
        {
            ReturnType = returnType;
            Expression = expression;
            Name = name;
        }
    }
}

좋은 웹페이지 즐겨찾기