C# 規則引擎
阿新 • • 發佈:2021-06-29
根據不同的城市以及購買數量,載入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; } } }