可編程表達式計算器
/// <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());
}
评论