解析字符串到C#拉姆达Func键 [英] Parse string to C# lambda Func

查看:151
本文介绍了解析字符串到C#拉姆达Func键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法来拉姆达的字符串表示形式转换为一个lambda Func键

Is there a way to convert string representation of lambda to a lambda Func?

Func<Product, bool> func = Parse<Product, bool>("product => product.Name.Length > 0");



我试过动态LINQ,但预期它不工作 - 例如,它不指望拉姆达。答案语法=>

I tried Dynamic LINQ but it doesn't work as expected - for example it doesn't expect lambda syntax =>.

摘要:


  • 写我自己的C#编译器 - 很搞笑

  • 发射了外部编译器(如CSC.EXE) - 很慢

  • 使用DLINQ - 正如我说我怎么没看到它可以解析的λ表达式

  • writing my own C# compiler - very funny
  • firing up external compiler (like csc.exe) - very slow
  • using DLINQ - as I said I don't see how it can parse lambda expressions

为什么我需要这样的:因为没有办法通过lambda表达式定制属性,如

Why do I need this: because there's no way to pass lambdas to custom attributes like

[Secure(role => role.CanDoThis && role.AllowedCount > 5)]

因此,作为一种解决方法,我想通过拉姆达为字符串:角色=> role.CanDoThis&安培; &功放; role.AllowedCount> 5。但是好像我将不得不使用DLINQ这样的:CanDoThis&放大器;&功放; AllowedCount> 5 - 因为那是语法它理解。但我的问题是关于真实的lambda表达式,我已经在询问时使用DLINQ。

So as a workaround I'd like to pass lambda as string: "role => role.CanDoThis && role.AllowedCount > 5". But seems like I'll have to use DLINQ like this: "CanDoThis && AllowedCount > 5" - since that's the syntax it understands. But my question was about true lambdas, I've already used DLINQ at the time of asking.

推荐答案

他们有很多LAMDA表达可用的解析器。其中有些是 LAMDA解析器 SPRACHE

They are many lamda expression parsers available. Some of them are Lamda-Parser, Sprache

示例代码:

例1:字符串连接和数字计算:

Example1 : string concat and number calculate:

string code = "2.ToString()+(4*2)"; // C# code Func<string> 
func = ExpressionParser.Compile<Func<string>>(code); // compile code 
string result = func(); // result = "28"

这篇关于解析字符串到C#拉姆达Func键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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