0

我的软件需要有某种规则库。无论如何我可以序列化一条规则吗?

为什么是单一规则?因为在实际执行规则引擎之前,我希望能够将一些特定规则添加到我的 RuleSet 中,并通过windows 工作流规则引擎执行该 RuleSet 。

根据此处给出的示例,我知道我可以序列化 RuleSet?

以下是其完成方式的简要说明:

1.创建对折扣属性的引用this.Discount

CodePropertyReferenceExpression discountProperty =  
    new CodePropertyReferenceExpression( 
    new CodeThisReferenceExpression(),  
    "Discount"); 

2. 创建对 orderValue 属性的引用

CodePropertyReferenceExpression orderValueProperty = 
    new CodePropertyReferenceExpression( 
        new CodeThisReferenceExpression(),  
        "OrderValue"); 

3. 在 orderValue 对象上定义条件

// if this.OrderValue > 500
RuleCondition discountCondition = new RuleExpressionCondition( 
    new CodeBinaryOperatorExpression( 
        orderValueProperty, 
        CodeBinaryOperatorType.GreaterThan, 
        new CodePrimitiveExpression(500))); 

4. 定义规则动作

// Create an action that sets the property Discount to 5% 
RuleStatementAction setDiscountAction = new RuleStatementAction( 
    new CodeAssignStatement(discountProperty,  
        new CodePrimitiveExpression(5))); 

5. 创建规则集

Rule discountRule = new Rule("CalculateDiscount"); 
discountRule.Condition = discountCondition; 
discountRule.ThenActions.Add(setDiscountAction); 
ruleSet = new RuleSet("DiscountRuleSet"); 
ruleSet.Rules.Add(discountRule); 

6. 序列化规则集

RuleDefinitions ruleDefinitions = new RuleDefinitions(); 
ruleDefinitions.RuleSets.Add(ruleSet); 
WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer(); 
XmlTextWriter writer = new XmlTextWriter("MyRules.rules", System.Text.Encoding.Unicode); 
serializer.Serialize(writer, ruleDefinitions); 
writer.Close();

7. 执行规则集

RuleEngine engine = new RuleEngine(ruleSet, typeof(Shopping));  
// execute the rule on a shopping object where OrderValue = 100 
// expect rule action to be not fired 
Shopping shoppingUnder500 = new Shopping(100); 
engine.Execute(shoppingUnder500); 
Console.WriteLine("shoppingUnder500 - Discount evaluated: " + shoppingUnder500.Discount); 

您可以在开头提到的链接中获得完整的示例。Pt 6 描述了如何持久化规则集。但我想知道我们是否可以序列化一个规则,它只不过是一个代码域条件表达式和一组语句(动作)(再次由代码域表示)。

或者在某处存储单个规则的更好方法是什么?

4

0 回答 0