How to add a new function to Ncalc

﹥>﹥吖頭↗ 提交于 2019-12-03 21:54:54

If I understand correctly:

As much as I was using it is by creating a static function

private static void NCalcExtensionFunctions(string name, FunctionArgs functionArgs)
{
    if (name == "yourfunctionname")
    {
        var param1 = functionArgs.Parameters[0].Evaluate();
        var param2 = functionArgs.Parameters[1].Evaluate();
        //... as many params as you require
        functionArgs.Result = (int)param1 * (int)param2; //do your own function logic here
    }
    if (name == "random")
    {
        if(functionArgs.Parameters.Count() == 0) 
        {
            functionArgs.Result = new Random().Next();
        }
        else if(functionArgs.Parameters.Count() == 1) 
        {
            functionArgs.Result = new Random().Next((int)functionArgs.Parameters[0].Evaluate());
        }
        else 
        {
            functionArgs.Result = new Random().Next((int)functionArgs.Parameters[0].Evaluate(), (int)functionArgs.Parameters[1].Evaluate());
        }
    }
}

And then you use it as follows

var expr = new Expression("yourfunctionname(3, 2)");
expr.EvaluateFunction += NCalcExtensionFunctions;
var result = expr.Evaluate();

var randExpr = new Expression("random(100)"); 
randExpr.EvaluateFunction += NCalcExtensionFunctions;
var resultRand = randExpr.Evaluate();

I hope I didn't mistype any of the code. A list of NCalc built-in functions can be found here: http://ncalc.codeplex.com/wikipage?title=functions&referringTitle=Home

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!