diff --git a/GFramework.Core/Functional/Result.cs b/GFramework.Core/Functional/Result.cs index 03508b5..2763a9d 100644 --- a/GFramework.Core/Functional/Result.cs +++ b/GFramework.Core/Functional/Result.cs @@ -12,12 +12,14 @@ // limitations under the License. using System.Diagnostics.Contracts; +using System.Runtime.InteropServices; namespace GFramework.Core.Functional; /// /// 表示一个无值的操作结果,仅包含成功或失败状态 /// +[StructLayout(LayoutKind.Auto)] public readonly struct Result : IEquatable { private readonly Exception? _exception; @@ -82,7 +84,7 @@ public readonly struct Result : IEquatable public static Result Failure(string message) { ArgumentException.ThrowIfNullOrWhiteSpace(message); - return new(false, new Exception(message)); + return new Result(false, new InvalidOperationException(message)); } /// @@ -113,10 +115,14 @@ public readonly struct Result : IEquatable [Pure] public bool Equals(Result other) { - // 比较状态和异常信息 - return _isSuccess == other._isSuccess && - (!IsFailure || (_exception?.GetType() == other._exception?.GetType() && - _exception?.Message == other._exception?.Message)); + if (_isSuccess != other._isSuccess) + return false; + + if (_isSuccess) + return true; + + return _exception!.GetType() == other._exception!.GetType() && + _exception.Message == other._exception.Message; } /// @@ -134,10 +140,7 @@ public readonly struct Result : IEquatable [Pure] public override int GetHashCode() { - // 根据状态和异常信息生成哈希码 - return IsSuccess - ? HashCode.Combine(true) - : HashCode.Combine(false, _exception?.GetType(), _exception?.Message); + return _isSuccess ? 1 : HashCode.Combine(_exception!.GetType(), _exception.Message); } /// @@ -164,5 +167,42 @@ public readonly struct Result : IEquatable /// Result 的字符串表示 [Pure] public override string ToString() => - IsSuccess ? "Success" : $"Fail({_exception?.Message ?? "Unknown"})"; + _isSuccess ? "Success" : $"Fail({_exception!.Message})"; + + /// + /// 尝试执行一个无返回值的操作,并根据执行结果返回成功或失败的 Result + /// + /// 要执行的无返回值操作 + /// 若操作成功执行返回成功的 Result,若执行过程中抛出异常则返回失败的 Result + [Pure] + public static Result Try(Action action) + { + try + { + action(); + return Success(); + } + catch (Exception ex) + { + return Failure(ex); + } + } + + /// + /// 将当前 Result 的成功结果映射为另一种类型的 Result + /// + /// 映射后的目标类型 + /// 用于转换值的函数 + /// 若当前为成功状态,返回包含转换后值的成功 Result;若为失败状态,返回保持原有错误的失败 Result + public Result Map(Func func) => + IsSuccess ? Result.Success(func()) : Result.Failure(_exception!); + + /// + /// 将当前 Result 绑定到一个返回 Result 的函数上 + /// + /// Result 中值的类型 + /// 返回 Result 的函数 + /// 若当前为成功状态,返回函数执行的结果;若为失败状态,返回保持原有错误的失败 Result + public Result Bind(Func> func) => + IsSuccess ? func() : Result.Failure(_exception!); } \ No newline at end of file