将表达式计算为字符串,返回对象?
基本上我有一些代码,当它发生时,我需要将某个对象设置为等于某个表达式。所有这些“做什么”爵士乐都存储为字符串。所以我解析它,并使用反射来查找我正在执行此操作的对象。现在我需要找出如何将值存储到该对象。问题是该值可能是“1”、“1*(5/2)”或“某个字符串值”。如果我可以有像“this.SomeProperty”或“(x > 3 ? 4 : 5)”这样的表达式,那就太酷了。
此外,它存储的对象至少可以是字符串、int、double 或 float。
Basically I have some code where when it happens, I need to set some object equal to some expression. All of this "what to do" jazz is stored as a string. So I parse it, and use reflection to find the object I am doing it to. Now I need to find out how to store the value to this object. The problem is the value could be "1", "1*(5/2)", or "some string value". It would be really cool if I could have expressions like "this.SomeProperty" or "(x > 3 ? 4 : 5)".
Also, the object it is storing to, could be a string, int, double, or float at the minimum.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
VS2008 示例包含一个漂亮的
ExpressionParser
,它可以用作通用表达式解析器 (VS2008 示例)。通过一些小的更新和自定义工厂类,我们可以将其变成更具表现力的东西:或者:
这些
Create
方法的返回类型是Func<>
实例,这意味着我们得到了很好的强类型委托:我已将代码推送到 gist
更新:我最近也在博客中提到了这一点。
更新2,另一个例子:
The VS2008 samples included a nifty
ExpressionParser
which could be used as a generic expression parser (VS2008 Samples). With a few small updates, and a custom factory class, we can turn it into something a bit more expressive:Or:
The return types of these
Create
methods areFunc<>
instances, which means we get nice strongly type delegates:I've push the code to a gist
Update: I've recently blogged about this too.
Update 2, another example:
您看过 http://ncalc.codeplex.com 吗?
它是可扩展的、快速的(例如有自己的缓存),使您能够在运行时通过处理 EvaluateFunction/EvaluateParameter 事件来提供自定义函数和变量。它可以解析的示例表达式:
它还处理 unicode &许多本地数据类型。如果您想更改语法,它会附带一个鹿角文件。还有一个支持 MEF 加载新功能的 fork。
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.