从 C# 中的字符串创建匿名方法
是否可以在 C# 中从字符串创建匿名方法?
例如,如果我有一个字符串 "x + y * z"
是否可以将其转换为某种方法/lambda 对象,我可以使用任意 x
,< code>y,z
参数?
is it possible to create an anonymous method in c# from a string?
e.g. if I have a string "x + y * z"
is it possible to turn this into some sort of method/lambda object that I can call with arbitrary x
,y
,z
parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是可能的,是的。您必须解析字符串,例如使用表达式树编译委托。
这是创建
(x, y, z) => 的示例x + y * z 使用表达式树:
It's possible, yes. You have to parse the string and, for example, compile a delegate using expression trees.
Here's an example of creating
(x, y, z) => x + y * z
using expression trees:只是为了使用 CodeDom 的乐趣(字符串中允许任何有效的 C# 代码,只要它存在于 mscorlib 中即可(根本不检查错误):
Just for fun using CodeDom (any valid C# code is allowed in the string as long as it is present in mscorlib (No check for errors at all):
C# 没有任何这样的功能(其他语言 - 比如 JavaScript - 有
eval
函数来处理这样的东西)。您需要解析该字符串并使用表达式树或通过发出 IL 自行创建一个方法。C# doesn't have any functionality like this (other languages - like JavaScript - have
eval
functions to handle stuff like this). You will need to parse the string and create a method yourself with either expression trees or by emitting IL..Net 框架中有执行此操作的功能。
这并不容易。您需要在该语句周围添加一些代码,以使其成为一个完整的程序集,包括您可以调用的类和方法。
之后,将字符串传递给
Here is an example
There are functionality to do this in the .Net framework.
It is not easy. You need to add some code around the statement to make it into a complete assembly including a class and method you can call.
After that you pass the string to
Here is an example
使用语法(例如 ANTLR)和创建表达式树的解释器是可能的。这不是一个小任务,但是,如果您限制接受输入的范围,您就可以成功。以下是一些参考资料:
以下是一些代码可能会转换的内容将 ANTLR ITree 转换为表达式树。它并不完整,但向您展示了您面临的挑战。
It could be possible with a grammar (e.g. ANTLR) and an interpreter which creates expression trees. This is no small task, however, you can be successful if you limit the scope of what you accept as input. Here are some references:
Here is what some code may look like to transform an ANTLR ITree into an Expression tree. It isn't complete, but shows you what you're up against.