基本信息
源码名称:C# 可编程表达式计算器 源码
源码大小:0.13M
文件格式:.rar
开发语言:C#
更新时间:2016-10-18
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
可編程表達式計算器


/// <summary> 
        ///將數學表達式轉化為C#程序
        /// </summary> 
        /// <param name="express ">用戶輸入的數學表達式</param> 
        /// <returns>返回C#程序代碼</returns> 
        public static string TranslateToCSharp(string express) 
        { 
            string s = ""; 
            if (File.Exists(Function.GetPathOfFunctionDll ())) 
            { 
                s = "using " Function.FunctionNameSpace ";\n"; 
            } 
             
            s = 
             "using System;\n"  
             "namespace ComputeUnit\n"  
             "{\n"  
                "public class Compute\n"  
                "{\n"  
                " public static double GetResult()\n"  
                " {\n"  
                " return " TranslateToCSharpExpress(express) ";\n"  
                " }\n"  
                " }"  
            "}\n";

            return s; 
        } 
     這裡的GetResult()函數也就是我們所說的函數F()
       
      3.3誰幫我們取得計算結果?
          反射!
          
          假設用戶輸入了表達式express,我們將如同下面的代碼所敘述的那樣計算它

          string source = TranslateUnit.TranslateToCSharp(express);

            //這裡加載了函數dll 
            string[] dlls = new string[1]; 
            dlls[0] = Function.GetPathOfFunctionDll(); //這裡加載了前面所說的Functions.dll 
             //編譯
            CompilerResults results = CompilerUnit.Compile (source, false,true, dlls,null);

            //重要:利用反射獲取計算結果
            if (results.Errors.Count == 0) 
            { 
                Assembly ass = results.CompiledAssembly;

                Type tp = ass.GetType("ComputeUnit.Compute");//ass.GetType("MyNamespace.MyClass");

                //獲取方法
                MethodInfo mi = tp.GetMethod("GetResult");//tp.GetMethod("MyMethodl");

                //創建實例
                Object obj = System.Activator.CreateInstance(tp);

                //執行方法
                try 
                { 
                    object res = mi.Invoke(obj, null); 
                    this.Output(res.ToString(), false, Color.Blue); //將計算結果輸出給用戶

                } 
                catch (Exception ex) 
                { 
                    MessageBox.Show(ex.ToString()); 
                }