问题
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