NFun
NFun copied to clipboard
How to cast(or convert) to some type ?
Hello!
Dictionary<string, Func<object>> varMap = new() {
["sec"] = () => DateTime.Now.Second
};
var calc = Funny.WithFunction("vars", (string name) => varMap[name]()).BuildForCalcConstant();
var result = calc.Calc("1 + vars('sec')");
Console.WriteLine(result);
These codes will cause NFun.Exceptions.FunnyParseException:“Invalid operator call argument: +(T0, T0)->T0. Expected: T0”
.
I want to cast or convert the object{int}
type to integer
or real
type, but I didn't found the usage in the examples.
Can you show me how to do this ?
Thanks !
Hi! As i see here - the func in the dictionary returns object, that means that vars
function returns any
type (object, in terms of C#)
But as far as Nfun has strict type system - it denies to sum any
and number
item, so you have the error.
to show it more clearly - lets simplify your code (in terms of types) like this:
var calc = Funny.WithFunction<string, object> ("vars", (string name) => new object()).BuildForCalcConstant();
var result = calc.Calc("1 + vars('sec')");
here you can see, that it is impossible to sum 1
and new object()
.
so, the solution is to change Func<object>
to Func<int>
:
Dictionary<string, Func<int>> varMap = new() {
["sec"] = () => DateTime.Now.Second
};
var calc = Funny.WithFunction("vars", (string name) => varMap[name]()).BuildForCalcConstant();
var result = calc.Calc("1 + vars('sec')");
Console.WriteLine(result);
or to use named typed function:
var calc = Funny.WithFunction("sec", () => DateTime.Now.Second).BuildForCalcConstant();
var result = calc.Calc("1 + sec()");
Console.WriteLine(result);