gpt4 book ai didi

c# - 使用方法的状态模式

转载 作者:行者123 更新时间:2023-11-30 15:00:16 25 4
gpt4 key购买 nike

我正在尝试基于状态模式的修改版本使用方法作为状态而不是类来实现一个简单的状态机,如下所示:

private Action<Input> currentState;
private void NextState(Input i) {
currentState(i);
}

private void State1(Input i) {
if( i ... )
currentState = State1;
else
currentState = State2;
}

private void State2(Input i) {
if( i ... )
currentState = State1;
else
currentState = State2;
}

但如果我可以这样做会更优雅:

private void NextState(Input i) {
currentState = currentState(i);
}

private Func<xxx> State1() {
if( i ... )
return State1;
else
return State2;
}

但是我不知道如何写这个Func。有办法做到这一点吗?

最佳答案

如果您想使用返回 void 的函数,请尝试使用 Action相反。

private Action State1() {
    if( ... )
        return State1Inner;
    else
        return State2Inner;
}

如果你想使用一个返回带有自己签名的函数的函数,你必须先定义一个自定义委托(delegate)类型。这是一个通用版本:

public delegate State<T> State<T>(T input);

private State<int> State1(int input) {
    if( ... )
        return State1;
    else
        return State2;
}

这将帮助您避免使用内部状态函数。

关于c# - 使用方法的状态模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15607074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com