How to add a new function to Ncalc

戏子无情 提交于 2019-12-05 04:21:21

问题


I'm using Ncalc in my new project and it already has almost everything I need .

I said almost everything, because now I need to expand some functions and also add new ones such as : nth root,random, etc

Do you know if anyone has already implemented those functions? Or could you give me any tips or guides to extend the function list of Ncalc???

Thanks in advance.


回答1:


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



来源:https://stackoverflow.com/questions/18875348/how-to-add-a-new-function-to-ncalc

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