C# - 我可以根据用户提供的字符串公式动态定义函数吗?
我可以使用 lambda 表达式定义一个 func,如下所示:
Func <int, int, int> Fxy = ( (a,b) => a + b ) ); // Fxy does addition
但是如果我想允许用户在运行时提供 lambda 表达式的 rhs 该怎么办?
String formula_rhs = Console.Readline();
// user enters "a - b"
我可以以某种方式修改 Fxy 吗,就像我已经编码一样,
Func <int, int, int> Fxy = ( (a,b) => a - b ) ); // Fxy does what the user wants
// (subtraction)
我目前使用自制的表达式解析器来接受用户定义的公式。刚启动 .NET,我感觉可能有一种不太痛苦的方法可以做到这一点。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试 ncalc 框架:http://ncalc.codeplex.com/
它简单且轻便。
Try the ncalc framework: http://ncalc.codeplex.com/
Its easy and lightweight.
没那么容易。 此库包含一些可用于转换 lambda 表达式的 Dynamic Linq 功能从text到Func<>,看一下。
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 命名空间用于动态代码生成。一般来说,它相当复杂,但可能对减法等简单函数有帮助。
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.
如果您计划使用不复杂的公式,JScript 引擎将提供简单的解决方案:
不要忘记添加对
Microsoft.JScript
程序集的引用If you are planning to use not complex formulas, JScript engine would easy solution:
Dont forget to add reference to
Microsoft.JScript
assembly使用 Linq.Expressions 可能是一个想法。
您的示例将转换为:
当然,您将享受将字符串解析为正确表达式的乐趣。 :-)
Using Linq.Expressions could be an idea here.
Your example would tranlate to:
Ofcourse, you will have the fun of parsing a string into the correct expressions. :-)