mirror of
https://github.com/GeWuYou/GFramework.git
synced 2026-03-22 10:34:30 +08:00
fix(state): 修改状态机切换方法返回值类型并改进转换失败处理
- 将ChangeTo方法返回值从void改为bool类型 - 添加转换失败时返回false的逻辑 - 在状态转换被拒绝时调用OnTransitionRejected回调 - 更新接口定义以匹配新的返回值类型 - 修改单元测试以验证转换失败时的返回值 - [skip ci]
This commit is contained in:
parent
f70254716b
commit
47326085e7
@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace GFramework.Core.Abstractions.state;
|
||||
@ -36,7 +36,8 @@ public interface IStateMachine
|
||||
/// 切换到指定类型的状态
|
||||
/// </summary>
|
||||
/// <typeparam name="T">要切换到的状态类型,必须实现IState接口</typeparam>
|
||||
void ChangeTo<T>() where T : IState;
|
||||
/// <returns>如果成功切换则返回true,否则返回false</returns>
|
||||
bool ChangeTo<T>() where T : IState;
|
||||
|
||||
/// <summary>
|
||||
/// 检查指定类型的状态是否已注册
|
||||
|
||||
@ -174,7 +174,7 @@ public class StateMachineTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 验证当当前状态拒绝转换时不应发生状态变化
|
||||
/// 验证当当前状态拒绝转换时不应发生状态变化
|
||||
/// </summary>
|
||||
[Test]
|
||||
public void ChangeTo_WhenCurrentStateDeniesTransition_Should_NotChange()
|
||||
@ -186,8 +186,9 @@ public class StateMachineTests
|
||||
_stateMachine.ChangeTo<TestStateV2>();
|
||||
|
||||
var oldState = _stateMachine.Current;
|
||||
_stateMachine.ChangeTo<TestStateV3>();
|
||||
var result = _stateMachine.ChangeTo<TestStateV3>();
|
||||
|
||||
Assert.That(result, Is.False);
|
||||
Assert.That(_stateMachine.Current, Is.SameAs(oldState));
|
||||
Assert.That(_stateMachine.Current, Is.SameAs(state1));
|
||||
Assert.That(state2.EnterCalled, Is.False);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
using GFramework.Core.Abstractions.state;
|
||||
using GFramework.Core.Abstractions.state;
|
||||
|
||||
namespace GFramework.Core.state;
|
||||
|
||||
@ -79,8 +79,9 @@ public class StateMachine(int maxHistorySize = 10) : IStateMachine
|
||||
/// 切换到指定类型的状态
|
||||
/// </summary>
|
||||
/// <typeparam name="T">目标状态类型</typeparam>
|
||||
/// <returns>如果成功切换则返回true,否则返回false</returns>
|
||||
/// <exception cref="InvalidOperationException">当目标状态未注册时抛出</exception>
|
||||
public void ChangeTo<T>() where T : IState
|
||||
public bool ChangeTo<T>() where T : IState
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
@ -90,10 +91,13 @@ public class StateMachine(int maxHistorySize = 10) : IStateMachine
|
||||
|
||||
// 验证当前状态是否可以转换到目标状态
|
||||
if (Current != null && !Current.CanTransitionTo(target))
|
||||
throw new InvalidOperationException(
|
||||
$"Cannot transition from {Current.GetType().Name} to {typeof(T).Name}");
|
||||
{
|
||||
OnTransitionRejected(Current, target);
|
||||
return false;
|
||||
}
|
||||
|
||||
ChangeInternal(target);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user