C# 在 .NET 中寻找简单的规则引擎库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/208659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:07:52  来源:igfitidea点击:

Looking for simple rules-engine library in .NET

c#.net.net-corelogicrule-engine

提问by Kurtz

Does anyone know of a good .NET library rules library (ideally open-source)? I need something that can do nested logic expressions, e.g., (A AND B) AND (B OR C OR D). I need to do comparisons of object properties, e.g., A.P1 AND B.P1. (Ideally, I could compare any property -- A.P1 AND B.P2).

有谁知道一个好的 .NET 库规则库(最好是开源的)?我需要一些可以执行嵌套逻辑表达式的东西,例如,(A AND B) AND (B OR C OR D)。我需要对对象属性进行比较,例如 A.P1 和 B.P1。(理想情况下,我可以比较任何属性——A.P1 和 B.P2)。

It should store the rules in a database (I've got a lot of simple configurable logic). And it should have a rule creation/management API. The management tool would have to inspect the instances to determine which properties are available and which constraints exist.

它应该将规则存储在数据库中(我有很多简单的可配置逻辑)。它应该有一个规则创建/管理 API。管理工具必须检查实例以确定哪些属性可用以及存在哪些约束。

Thanks!

谢谢!



Oh, one more thing. As a rules-engine, I need to include the concept of Actions (Commands). These are what execute when the expression returns:

哦,还有一件事。作为规则引擎,我需要包含操作(命令)的概念。这些是表达式返回时执行的内容:

If (expression.Evaluation) { actions.Execute(); }

So I see a rule as something like:

所以我认为一个规则是这样的:

class Rule
{
    Expression Exp;
    Actions[] Actions;
    Run() 
    { 
        if(Exp.Evaluate()) 
        { 
            foreach(action in Actions) 
            { 
                action.Execute(); 
            }
        } 
    }
}

回答by Kurtz

The official MS solution for this is Windows Workflow. Although I wouldn't call it "simple", it meets all of your specifications (which would require an extensive framework to meet, anyhow).

对此的官方 MS 解决方案是Windows Workflow。尽管我不会称其为“简单”,但它满足您的所有规范(无论如何,这需要一个广泛的框架才能满足)。

回答by James Curran

Well, since logical expression are just a subset of mathematical expression, you may want to try NCalc - Mathematical Expressions Evaluator for .NETover on CodePlex.

好吧,由于逻辑表达式只是数学表达式的一个子集,您可能想在 CodePlex 上尝试NCalc - .NET 的数学表达式评估器

回答by Hector Sosa Jr

None of the open sourced .NET rules-engine have support for storing rules in the database. The only ones that stored the rules in a database are commercial. I've created some UIs for custom rule engines that run off the database, but this can be non-trivial to implement. That's usually the main reason you won't see that feature for free.

没有任何开源的 .NET 规则引擎支持在数据库中存储规则。唯一将规则存储在数据库中的规则是商业规则。我已经为从数据库运行的自定义规则引擎创建了一些 UI,但这可能很难实现。这通常是您不会免费看到该功能的主要原因。

As far as I know, none of them will meet all of your criteria, but here is a list of the ones I know of:

据我所知,它们都不能满足您的所有标准,但这里列出了我所知道的标准:

Simplest one is SRE
http://sourceforge.net/projects/sdsre/

最简单的一种是 SRE
http://sourceforge.net/projects/sdsre/

One with rule management UI is NxBRE
http://www.agilepartner.net/oss/nxbre/

一个规则管理 UI 是 NxBRE
http://www.agilepartner.net/oss/nxbre/

Drools.NET uses JBOSS rules
http://droolsdotnet.codehaus.org/

Drools.NET 使用 JBOSS 规则
http://droolsdotnet.codehaus.org/

I personally haven't used any of them, because all of the projects I worked with never wanted to use something built in-house. Most business think that this is pretty easy to do, but end up wasting too much time coding and implementing it. This is one of those areas that the Not Invented Here Syndrome (NIH) rules.

我个人没有使用过它们中的任何一个,因为我参与的所有项目都不想使用内部构建的东西。大多数企业认为这很容易做到,但最终会浪费太多时间进行编码和实施。这是此处非发明综合症 (NIH) 规定的领域之一。

回答by Shaun Bowe

Here is a class I have used in the past. It evaluates strings just like eval() does in Javascript.

这是我过去使用过的一个类。它评估字符串就像 eval() 在 Javascript 中所做的一样。

String result = ExpressionEvaluator.EvaluateToString("(2+5) < 8");

All you need to do is construct a string to be evaluated from your business objects and this will take care of all the complicated nested logic etc.

您需要做的就是构造一个字符串以从您的业务对象中进行评估,这将处理所有复杂的嵌套逻辑等。

using System;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Reflection;
using Microsoft.JScript;

namespace Common.Rule
{
  internal static class ExpressionEvaluator
  {
    #region static members
    private static object _evaluator = GetEvaluator();
    private static Type _evaluatorType;
    private const string _evaluatorSourceCode =
        @"package Evaluator
            {
               class Evaluator
               {
                  public function Eval(expr : String) : String 
                  { 
                     return eval(expr); 
                  }
               }
            }";

    #endregion

    #region static methods
    private static object GetEvaluator()
    {
      CompilerParameters parameters;
      parameters = new CompilerParameters();
      parameters.GenerateInMemory = true;

      JScriptCodeProvider jp = new JScriptCodeProvider();
      CompilerResults results = jp.CompileAssemblyFromSource(parameters, _evaluatorSourceCode);

      Assembly assembly = results.CompiledAssembly;
      _evaluatorType = assembly.GetType("Evaluator.Evaluator");

      return Activator.CreateInstance(_evaluatorType);
    }

    /// <summary>
    /// Executes the passed JScript Statement and returns the string representation of the result
    /// </summary>
    /// <param name="statement">A JScript statement to execute</param>
    /// <returns>The string representation of the result of evaluating the passed statement</returns>
    public static string EvaluateToString(string statement)
    {
      object o = EvaluateToObject(statement);
      return o.ToString();
    }

    /// <summary>
    /// Executes the passed JScript Statement and returns the result
    /// </summary>
    /// <param name="statement">A JScript statement to execute</param>
    /// <returns>The result of evaluating the passed statement</returns>
    public static object EvaluateToObject(string statement)
    {
      lock (_evaluator)
      {
        return _evaluatorType.InvokeMember(
                    "Eval",
                    BindingFlags.InvokeMethod,
                    null,
                    _evaluator,
                    new object[] { statement },
                    CultureInfo.CurrentCulture
                 );
      }
    }
    #endregion
  }    
}

回答by Scott Dorman

Depending on what you are trying to do using Lambda expressions (and expression trees) can work for this concept. Essentially, you provide an expression as a string that is then compiled on the fly into a lambda expression/expression tree, which you can then execute (evaluate). It's not simple to understand at first, but once you do it's extremely powerful and fairly simple to set up.

根据您尝试使用 Lambda 表达式(和表达式树)执行的操作,此概念适用。本质上,您将表达式作为字符串提供,然后将其即时编译为 lambda 表达式/表达式树,然后您可以执行(评估)该树。一开始并不容易理解,但是一旦你做到了,它就会非常强大并且设置起来相当简单。

回答by Nicolai Ustinov

Agreeing with will I would say use something from the workflow engine family although not workflow. Examine System.Workflow.Activities.RulesNamespace a little bit - it's supported in .Net 3, and built into .Net3.5. You have everything in hand for free to use like you mentioned :

同意我会说使用工作流引擎系列中的东西,尽管不是工作流。稍微检查一下System.Workflow.Activities.Rules命名空间 - 它在 .Net 3 中受支持,并内置于 .Net3.5 中。您可以像您提到的那样免费使用所有东西:

  • RuleCondition for conditions , RuleAction for actions

  • standardized format for describing metacode (CodeDom - CodeExpressions)

  • you can plugin any kind of complexity into that (to tell the truth except Linq and lambdas and so extension methods of some kind) via TypeProviders

  • there's a builtin editor for rule editing with intellisense

  • as the rule is serializable it can be easily persisted

  • if you meant to use the rules over a database scheme then via typeprovider it can be implemented too
  • 条件的 RuleCondition ,动作的 RuleAction

  • 用于描述元代码的标准化格式(CodeDom - CodeExpressions)

  • 您可以通过 TypeProviders 将任何类型的复杂性插入其中(说实话,除了 Linq 和 lambdas 以及某种扩展方法)

  • 有一个内置的编辑器,用于使用智能感知进行规则编辑

  • 因为规则是可序列化的,所以它可以很容易地持久化

  • 如果您打算在数据库方案上使用规则,那么也可以通过 typeprovider 实现

For a starter : Using rules outside of a workflow

首先: 在工作流之外使用规则

Ps.: we're using it extensively and there're much more in that namespace than you ever imagine -> a complete meta algorithm language

Ps.:我们正在广泛使用它,并且该命名空间中的内容比您想象的要多得多 -> 一种完整的元算法语言

And the most important : it's easy to use - really

最重要的是:它易于使用 - 真的

回答by Brian Ellis

I would look at Windows Workflow. Rules engines and workflow tend to start simple and get progressively more complex. Something like Windows Workflow Foundation is not too difficult to start with and provides room for growth. Here is a post that shows it's not too difficult to get a simple workflow engine going.

我会看看 Windows 工作流。规则引擎和工作流往往从简单开始,然后逐渐变得复杂。像 Windows Workflow Foundation 这样的东西入门并不难,并且提供了增长空间。 这是一篇文章,表明启动一个简单的工作流引擎并不太难。

回答by Brendan Kowitz

Maybe check out SmartRules. Its not free, but the interface looks simple enough.

也许查看SmartRules。它不是免费的,但界面看起来很简单。

Only know about it because I've used the SmartCode codegen utility from there before.

只知道它是因为我以前从那里使用过 SmartCode 代码生成实用程序。

Here is an example rule from the Website:

这是来自网站的示例规则:

BUSINESS RULES IN NATURAL LANGUAGE      

Before
If (Customer.Age > 50 && Customer.Status == Status.Active) {
policy.SetDiscount(true, 10%);
}

After (with Smart Rules)
If Customer is older than 50 and
the Customer Status is Active Then
Apply 10 % of Discount

回答by Hugo Rodger-Brown

It's not free, as you can't easily untangle it from its BizTalk parentage, but the Business Rules Engine components of BizTalk are a separate entity from the core BizTalk engine itself, and comprise a very powerful rules engine that includes a rules / policy based GUI. If there was a free version of this it would fit your requirements (buying BizTalk just for the BRE wouldn't really work commercially.)

它不是免费的,因为您不能轻易地从 BizTalk 的起源中解开它,但是 BizTalk 的业务规则引擎组件是一个独立于核心 BizTalk 引擎本身的实体,并且包含一个非常强大的规则引擎,其中包括基于规则/策略的图形用户界面。如果有免费版本,它会满足您的要求(仅为 BRE 购买 BizTalk 并不能真正用于商业用途。)

回答by Sentient

Windows Workflow Foundation does give you a free forward chaining inference engine. And you can use it without the workflow part. Creating and Editing rules is ok for developers.

Windows Workflow Foundation 确实为您提供了一个免费的前向链接推理引擎。您可以在没有工作流部分的情况下使用它。开发人员可以创建和编辑规则。

If you want to have non-programmers edit and maintain the rules you can try out the Rule Manager.

如果您想让非程序员编辑和维护规则,您可以尝试使用规则管理器

The Rule Manager will generate a working visual studio solution for you. That should get you started rather quickly. Just click on File \ Export and selecte the WFRules format.

规则管理器将为您生成一个有效的 Visual Studio 解决方案。这应该可以让你很快开始。只需单击文件\导出并选择 WFRules 格式。