开发者

C# - can I define a function on the fly from a user-supplied string formula?

I can define a func with a lambda expression as in:

Func <int, int, int> Fxy = ( (a,b) => a + b ) );  // Fxy does addition

But what if I wanted to allow the user to supply the r.h.s. of the lambda expression at runtime ?

String formula_rhs = Console.Readline();
// user enters "a - b"

Can 开发者_Python百科I somehow modify Fxy as if I had coded

Func <int, int, int> Fxy = ( (a,b) => a - b ) );  // Fxy does what the user wants 
                                                  // (subtraction)

I presently use a home built expression parser to accept user-defined formulas. Just starting up w .NET, and I get the feeling there may be a not-too-painful way to do this.


Try the ncalc framework: http://ncalc.codeplex.com/ Its easy and lightweight.


Is not so easy. This library contains some Dynamic Linq features you can use to convert a lambda expression from text to Func<>, have a look at it.


System.Reflection.Emit namespace is intended for code generation on-the-fly. It is quite complicated in general but may help for simple functions like subtraction.


If you are planning to use not complex formulas, JScript engine would easy solution:

        Microsoft.JScript.Vsa.VsaEngine engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
        MessageBox.Show(Microsoft.JScript.Eval.JScriptEvaluate("((2+3)*5)/2", engine).ToString());

Dont forget to add reference to Microsoft.JScript assembly


Using Linq.Expressions could be an idea here.

Your example would tranlate to:

var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var sum = Expression.Subtract(a, b);
var lamb = Expression.Lambda<Func<int, int, int>>(sum, a, b);
Func<int, int, int> Fxy = lamb.Compile();

Ofcourse, you will have the fun of parsing a string into the correct expressions. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜