C#中:如何分析任意字符串到EX pression树? [英] C#: How to parse arbitrary strings into expression trees?

查看:169
本文介绍了C#中:如何分析任意字符串到EX pression树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的工作我有一个相当奇怪的数据源工作的项目。我可以给它一个查询,它将返回我的DataTable。但查询是不是一个传统的字符串。它更像是......一组定义了我想要的标准方法调用。这些方针的东西:

In a project that I'm working on I have to work with a rather weird data source. I can give it a "query" and it will return me a DataTable. But the query is not a traditional string. It's more like... a set of method calls that define the criteria that I want. Something along these lines:

var tbl = MySource.GetObject("TheTable");
tbl.AddFilterRow(new FilterRow("Column1", 123, FilterRow.Expression.Equals));
tbl.AddFilterRow(new FilterRow("Column2", 456, FilterRow.Expression.LessThan));
var result = tbl.GetDataTable();

在本质上,它支持所有标准的东西(布尔运算,括号混合,一些功能等等),但语法写它是相当冗长,不舒服的日常使用。

In essence, it supports all the standard stuff (boolean operators, parantheses, a few functions, etc.) but the syntax for writing it is quite verbose and uncomfortable for everyday use.

我想作一个小的解析器将解析给定的EX pression(如列1 = 123列2< 456),并将其转换为上述函数调用。此外,这将是很好,如果我能有添加参数,所以我会受到保护,免受注入攻击。最后的小片糖在顶部将是如果它可以缓存解析结果,并重新使用它们时相同的查询是在另一目的是重新执行

I wanted to make a little parser that would parse a given expression (like "Column1 = 123 AND Column2 < 456") and convert it to the above function calls. Also, it would be nice if I could add parameters there, so I would be protected against injection attacks. The last little piece of sugar on the top would be if it could cache the parse results and reuse them when the same query is to be re-executed on another object.

所以我想知道 - 在那里,我可以用这个任何现有的解决方案,否则我将不得不推出自己的EX pression解析器?这不是太复杂,但如果我能拯救自己的编码两三天的臭虫heapload来解决,这将是值得的。

So I was wondering - are there any existing solutions that I could use for this, or will I have to roll out my own expression parser? It's not too complicated, but if I can save myself two or three days of coding and a heapload of bugs to fix, it would be worth it.

推荐答案

试用反讽。虽然资料缺乏,样品将让你和非常快速运行。具有讽刺意味的​​是解析code和构建抽象语法树的一个项目,但你可能需要编写一些逻辑来创建适合您需要的形式。该 DLR 可能是补充这一点,因为它可以动态地生成/从抽象语法树执行code(这是用于IronPython和IronRuby的)。这两个应该做一个很好的一对。

Try out Irony. Though the documentation is lacking, the samples will get you up and running very quickly. Irony is a project for parsing code and building abstract syntax trees, but you might have to write a little logic to create a form that suits your needs. The DLR may be the complement for this, since it can dynamically generate / execute code from abstract syntax trees (it's used for IronPython and IronRuby). The two should make a good pair.

哦,他们都是一流的。NET解决方案和开源。

Oh, and they're both first-class .NET solutions and open source.

这篇关于C#中:如何分析任意字符串到EX pression树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆