NCalc 學習筆記 (六)

參數

靜態參數

靜態參數能夠在表達式求值前定義。用方括號括起來表示爲靜態參數。
能夠經過 Expression 對象中名爲 Parameters 的字典來訪問靜態參數。性能

Expression e = new Expression("2 * [x] ^ 2 + 5 * [y]");
e.Parameters["x"] = 5;
e.Parameters["y"] = 1;

Console.WriteLine(e.Evaluate());

參數十分有用,有些編譯時不知道的值能夠在運行時再進行賦值。或者在性能顯得十分重要時,能夠用參數來保存中間結果。lua

表達式參數

一個表達式能夠由多個表達式經過表達式參數鏈接起來。簡單來講就是把表達式當參數用。code

Expression volume = new Expression("[surface] * h");
Expression surface = new Expression("[l] * [L]");
volume.Parameters["surface"] = surface;
surface.Parameters["l"] = 1;
surface.Parameters["L"] = 2;

動態參數

有的時候參數可能很複雜而須要用一個專用的方法來進行求值。咱們能夠使用 Expression 對象提供的 EvaluateParameter 事件。這樣,當某個參數沒法再字典中找到時,NCalc 就會嘗試調用 EvaluateParameter 事件來解決這個問題。對象

方括號參數

用方括號括起來的參數能夠支持 .,而且支持數字開頭的參數。事件

Expression e = new Expression("[1My First Parameter] + [2My Second Parameter]");

多值參數

若是參數是 IEnumerable 類型,而且使用了 EvaluationOptions.IterateParameters 選項,那麼求值結果是一個 IList 類型的對象。get

Expression e = new Expression("(a * b) ^ c", EvaluateOptions.IterateParameters);
e.Parameters["a"] = new int[] { 1, 2, 3, 4, 5 };
e.Parameters["b"] = new int[] { 6, 7, 8, 9, 0 };
e.Parameters["c"] = 3;

foreach (var result in (IEnumerable)e.Evaluate())
{
    Console.WriteLine(result);
}

// 5
// 13
// 27
// 39
// 3

注: ^ 並非冪乘符號,它表明的是異或。it


參考連接

NCalc - Mathematical Expressions Evaluator for .NETio

相關文章
相關標籤/搜索