Aet*_*oud 17 c# logic matrix control-structure decision-tree
我需要根据一组相当大的8个相关依赖条件做出决定.
| A | B | C | D | E | F | G | H
-----------+---+---+---+---+---+---+---+---
Decision01 | 0 | 1 | - | 1 | 0 | 1 | - | 1
Decision02 | 1 | 0 | - | 0 | 0 | - | 1 | -
...
Decision11 | 1 | 0 | 1 | 1 | 1 | - | 1 | 1
Run Code Online (Sandbox Code Playgroud)
从A到H的每个条件对于决定可以是真(1),假(0)或不相关( - ).
所以用给定的输入
A B C D E F G H
1 0 1 0 0 1 1 1
Run Code Online (Sandbox Code Playgroud)
它应该评估为Decision02.
决策是明确的,因此从任何给定的输入条件集中,必须明确哪个决策(并且在决策矩阵未涵盖的情况下,应抛出异常).
在我之前在这个项目上工作过的开发人员试图将其作为一个500行长嵌套来实现 - 如果这个庞然大物当然是有点儿的,并且不可维护.
所以我搜索了实现这样一个逻辑的最佳方法,并且我遇到了决策表/查找表/控制表.
我发现了很多决策表生成器,但没有关于如何实现决策过程的单一代码:(
我可以在底层MSSQL数据库中创建决策表,或者在代码,xml或其他任何内容中创建决策表.我只需要一些关于如何实现这一点的指示.
实现此逻辑的最佳实践是什么?字典?多维数组?完全不同的东西?
你可以用Func数组来做.
static Func<bool,bool> isTrue = delegate(bool b) { return b; };
static Func<bool,bool> isFalse = delegate(bool b) { return !b; };
static Func<bool,bool> isIrrelevant = delegate(bool b) { return true; };
Run Code Online (Sandbox Code Playgroud)
现在你可以把你的矩阵放到一个像这样的字典中:
Dictionary<string,Func<bool,bool>[]> decisionMatrix = new Dictionary<string,Func<bool,bool>[]>();
// 0 | 1 | - | 1 | 0 | 1 | - | 1
matrix.Add("Decision01", new Func<bool,bool>{isFalse, isTrue, isIrrelevant, isTrue, isFalse, isTrue, isIrrelevant, isTrue});
Run Code Online (Sandbox Code Playgroud)
最后为每个给定的输入数组:
bool[] input = new bool[]{ false, true, false, true, false, true, false, true}
string matchingRule = null;
foreach( var pair in matrix ) {
bool result = true;
for( int i = 0; i < input.Length; i++) {
// walk over the function array and call each function with the input value
result &= pair.Value[i](input[i]);
}
if (result) { // all functions returned true
// we got a winner
matchingRule = pair.Key;
break;
}
}
// matchingRule should now be "Decision01"
Run Code Online (Sandbox Code Playgroud)
这可能应该得到一些更多的检查(例如检查输入数组是否具有正确的大小),但应该给你一些想法.使用Funcs还可以在获得第四个状态时提供更多灵活性.