我正在研究一些规则引擎,我遇到了 Microsoft RulesEngine:https://microsoft.github.io/RulesEngine/。它看起来非常有前途,因为我在规则和输入方面获得了很大的灵活性。然而,当我尝试对扩展表达式自定义类/类型进行选择/投影时,我遇到了一些问题。
这是场景。给定输入:
"reportId": "r1",
"reportVersionId": 2,
"defects": [
{
"id": "d1",
"isMerging": true,
"mergeDefectId": "d2",
"state": "open",
"defectStartPoint": 2,
"defectEndPoint": 10
},
{
"id": "d2",
"isMerging": true,
"state": "close",
"defectStartPoint": 8,
"defectEndPoint": 15
},
{
"id": "d3",
"isMerging": false,
"state": "open",
"defectStartPoint": 1,
"defectEndPoint": 5
}
]
我想对此列表执行一些更复杂的检查(仅举一个例子:如果其中一个缺陷具有“status”:“open”和“isMerging”:true,则检查 MergingDefectId 是否为有效 id(另一个缺陷具有该 ID) id 存在并且该缺陷有效))。因此基于此:https://microsoft.github.io/RulesEngine/#extending-expression-via-custom-classtype-injection我创建了这个类:
public static class ComplexRulesMethods
{
public static bool IsValid(object input)
{
//Perform complex logic
return true;
}
}
对于规则文件我有:
[
{
"WorkflowName": "workflowName",
"Rules": [
{
"RuleName": "ruleName",
"ErrorMessage": "errorMessage",
"ErrorType": "Error",
"RuleExpressionType": "LambdaExpression",
"Expression": "ComplexRulesMethods.IsValid(input1.currentVersion.defects.Select( new {id as id, isMerging as isMerging, mergeDefectId as mergeDefectId} ))"
}
]
}
]
计划使 IsValid(object input) 通用,因此它将能够验证具有“id”、“isMerging”和“mergedDefectId”属性的对象列表。如果我得到另一个可以进行验证的输入,我将创建另一个表达式并将新的输入字段映射到这 3 个(“id”、“isMerging”和“mergedDefectId”)。
问题是,每当我想执行具有多个属性的选择(
"Expression": "ComplexRulesMethods.IsValid(input1.defects.Select(id))" works fine
)时,我都会得到
这个错误:
Exception while parsing expression ComplexRulesMethods.IsValid(input1.defects.Select( new {id as id, isMerging as isMerging, mergeDefectId as mergeDefectId} )) - No property or field 'id' exists in type 'Boolean'
。
我尝试了使用 () 而不是 {} 的多种变体,带或不带“it”。但我总是收到该错误,而且我不知道确切的原因,以及我想要的是否实际上是可能的。
我认为你需要使用
( )
而不是 { }
。
就像这样:
"ComplexRulesMethods.IsValid(input1.currentVersion.defects.Select( new (id as id, isMerging as isMerging, mergeDefectId as mergeDefectId) ))"
另请参阅 GitHub 项目页面上的 this 链接。