委托
本页说明控制算法需要切换处理策略时应如何组织代码。运行时委托、方法组变量、多播回调和预定义函数对象当前不可用。调用目标必须在编译期明确。
用命名方法选择策略
class Controller
{
private int Standard(int error)
{
return error * 2;
}
private int Aggressive(int error)
{
return error * 4;
}
public int Calculate(int mode, int setpoint, int actual)
{
int error = setpoint - actual;
if (mode == 1)
{
return Aggressive(error);
}
return Standard(error);
}
}
Controller controller = new Controller();
int output = controller.Calculate(1, 100, 95);
适用规则
- 策略数量固定:使用整数模式或枚举配合分支。
- 多个步骤都要执行:按明确顺序直接调用命名方法。
- 设备类型不同:使用接口和编译期确定的实现类型。
- 不把方法保存到变量、集合或对象字段中。
定长数组上的单参数表达式形式见 匿名表达式。那不是可保存的运行时委托。
当前不可用
delegate声明、Func/Action/Predicate;- 方法组赋值、多播
+=/-=; - 把回调存进字段再在扫描中间接调用;
- 语句体 lambda、闭包和任务回调。