C𞃳動的実行文字列(動的作成コード)

36563 ワード

C〓〓のプログラムを編纂する時、私達は動態的にいくつかコードを生成して実行する必要があります.しかし、C〓〓はJavaScriptと違って、Eva関数があります.コードを動的に実行できます.これらの機能は全部自分で完成します.次のように実例を示します
動的作成コード:
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; 
"); code.Append("using System.Data;
"); code.Append("using System.Data.SqlClient;
"); code.Append("using System.Data.OleDb;
"); code.Append("using System.Xml;
"); code.Append("namespace EvalGuy {
"); // EvalGuy, code.Append(" public class _Evaluator {
"); // _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("}
"); // } 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}
", 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; } } }
 
呼び出し方法:EvaalGry名前空間を参照してください.
Console.WriteLine("Test0: {0}", Evaluator.EvaluateToInteger("(30 + 4) * 2"));   
Console.WriteLine("Test1: {0}", Evaluator.EvaluateToString("\"Hello \" + \"There\""));   
Console.WriteLine("Test2: {0}", Evaluator.EvaluateToBool("30 == 40"));   
Console.WriteLine("Test3: {0}", Evaluator.EvaluateToObject("new DataSet()"));   

EvaluatorItem[] items = {   
                          new EvaluatorItem(typeof(int), "(30 + 4) * 2", "GetNumber"),   
                          new EvaluatorItem(typeof(string), "\"Hello \" + \"There\"",    
                                                            "GetString"),   
                          new EvaluatorItem(typeof(bool), "30 == 40", "GetBool"),   
                          new EvaluatorItem(typeof(object), "new DataSet()", "GetDataSet")   
                        };   

Evaluator eval = new Evaluator(items);   
Console.WriteLine("TestStatic0: {0}", eval.EvaluateInt("GetNumber"));   
Console.WriteLine("TestStatic1: {0}", eval.EvaluateString("GetString"));   
Console.WriteLine("TestStatic2: {0}", eval.EvaluateBool("GetBool"));   
Console.WriteLine("TestStatic3: {0}", eval.Evaluate("GetDataSet"));
 
回転:http://hi.baidu.com/yxw740/item/e4d256f2208590d342c36acc