评估 .NET 中的动态字符串公式?
我正在开发一个项目,需要评估 VB.NET 中的一些公式。我一直在使用 MS 脚本控件评估一些简单的逻辑/数学公式。
但是,我现在面临着处理将程序中的变量设置为某些值的字符串表达式。因此,举例来说,假设我有以下内容:
Dim netPrice As Decimal
Dim expressionFormula As String = "netPrice = 0"
我需要能够计算“expressionFormula”并将 netPrice 变量设置为 0。我一直在尝试 MS 脚本控件中 .AddObject 方法的不同组合,但还没有任何效果。
我应该提到这个示例仅用于说明目的,实际场景涉及来自类型化 DataSet 的多个 DataTable 对象。最后,我的DataTable中的一些字段可能需要根据这些动态表达式设置为特定的常量值。
感谢您的帮助!
I'm working on a project where I need to evaluate some formulas in VB.NET. I've been using the MS Script Control to evaluate some of the simple logical/mathematical formulas.
However, I'm now faced with dealing with string expressions that set variables in my program to certain values. So, for example, let's say I've got the following:
Dim netPrice As Decimal
Dim expressionFormula As String = "netPrice = 0"
I need to be able to evaluate "expressionFormula" and set the netPrice variable to 0. I've been trying different combinations of the .AddObject method in the MS Script Control, but nothing's worked yet.
I should mention this example is only for illustration purposes, the real scenario involves several DataTable objects from a typed DataSet. In the end, some of the fields in my DataTable may need to be set to specific constant values based on these dynamic expressions.
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于这种功能,您需要编写自己的解析器和评估器。
查看 Linq
表达式
类 - 它可能会有所帮助。或者,根据您的方法,您可以使用
CSharpCodeProvider
将表达式编译为 C# 类/程序集。For this kind of functionality, you will need to write your own parser and evaluator.
Take a look at the Linq
Expression
class - it may help.Alternatively, depending on your approach, you may be able to write and compile dynamic classes using the
CSharpCodeProvider
to compile your expressions as C# classes/assemblies.如果您必须处理复杂的表达式,也许这个库会有所帮助:http://flee.codeplex.com/ ?
If you have to handle complex expressions, maybe this library can be helpful : http://flee.codeplex.com/ ?
Dynamic Linq 就是您正在寻找的
Dynamic Linq is what you're looking for