C# 规则引擎

根据不同的城市以及购买数量,加载json文件,得到优化折扣,运行结果:

  

DisCount.json

[
  {
    "WorkflowName": "Discount",
    "Rules": [
      {
        "RuleName": "rule1",
        "SuccessEvent": "9",
        "ErrorMessage": "One or more adjust rules failed.",
        "ErrorType": "Error",
        "RuleExpressionType": "LambdaExpression",
        "Expression": "input1.city == \"厦门\" AND input2.totalOrders >=0"
      },
      {
        "RuleName": "rule2",
        "SuccessEvent": "8",
        "ErrorMessage": "One or more adjust rules failed.",
        "ErrorType": "Error",
        "RuleExpressionType": "LambdaExpression",
        "Expression": "input1.city == \"泉州\" AND input2.totalOrders >=1"
      }
    ]
  }
]

 

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using RulesEngine.Extensions;
using RulesEngine.Models;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Windows.Forms;

namespace RulesEngineDemo
{
    public partial class MainForm : Form
    {
        // NuGet -> RulesEngine

        public MainForm()
        {
            InitializeComponent();

            cmbCity.SelectedIndex = 0;
        } 

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            string city = cmbCity.Text;
            string count = txtCount.Text.Trim();

            var basicInfo = "{\"city\": \"" + city +"\"}";
            var orderInfo = "{\"totalOrders\": " + count + "}";

            var converter = new ExpandoObjectConverter();

            dynamic input1 = JsonConvert.DeserializeObject<ExpandoObject>(basicInfo, converter);
            dynamic input2 = JsonConvert.DeserializeObject<ExpandoObject>(orderInfo, converter);

            var inputs = new dynamic[]
            {
              input1,
              input2
            };

            // 加载规则
            var files = Directory.GetFiles(Directory.GetCurrentDirectory(), "Discount.json", SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
            {
                lblMsg.Text = "Rules not found.";
                return;
            }

            var fileData = File.ReadAllText(files[0]);
            var workflowRules = JsonConvert.DeserializeObject<List<WorkflowRules>>(fileData);

            // 初始化规则引擎
            var bre = new RulesEngine.RulesEngine(workflowRules.ToArray(), null);

            string note = "没有折扣";

            // 执行规则
            List<RuleResultTree> resultList = bre.ExecuteAllRulesAsync("Discount", inputs).Result;

            // 处理结果
            resultList.OnSuccess((eventName) =>
            {
                note = $"打 {eventName} 折";
            });

            resultList.OnFail(() =>
            {
                note = "不打折";
            });

            lblMsg.Text = note;
        }
    }
}

 

posted @ 2021-06-29 15:08  CHHC  阅读(866)  评论(0编辑  收藏  举报