fix(result): 修复Result扩展和异常处理逻辑

- 在Combine方法中添加对Bottom状态的检查和处理
- 使用IfSucc方法简化成功状态下的值添加逻辑
- 修正泛型绑定示例中的语法错误
- 在FromNullable和FromNullableStruct方法中使用nameof获取参数名称
- 改进Exception属性的文档说明并优化异常消息
- 在Try方法中添加对空函数的验证
This commit is contained in:
GeWuYou 2026-02-25 20:16:19 +08:00 committed by gewuyou
parent 61349a83ab
commit 1d50dc2224
2 changed files with 16 additions and 6 deletions

View File

@ -46,8 +46,11 @@ public static class ResultExtensions
if (result.IsFaulted)
return Result<List<T>>.Fail(result.Exception);
if (result.IsBottom)
return Result<List<T>>.Fail(new InvalidOperationException("Cannot combine Bottom results"));
if (result.IsSuccess)
values.Add(result.Match(succ: v => v, fail: _ => throw new InvalidOperationException()));
result.IfSucc(values.Add);
}
return Result<List<T>>.Succeed(values);
@ -101,7 +104,7 @@ public static class ResultExtensions
/// var result = Result&lt;int&gt;.Succeed(42);
/// var bound = await result.BindAsync(async x =>
/// await GetUserAsync(x) is User user
/// User&gt;.Succeed(user)
/// ? Result&lt;User&gt;.Succeed(user)
/// : Result&lt;User&gt;.Fail(new Exception("User not found")));
/// </code>
/// </example>
@ -262,7 +265,7 @@ public static class ResultExtensions
string errorMessage = "Value is null") where T : class =>
value is not null
? Result<T>.Succeed(value)
: Result<T>.Fail(new ArgumentNullException(errorMessage));
: Result<T>.Fail(new ArgumentNullException(nameof(value), errorMessage));
/// <summary>
/// 将可空值类型转换为 Result
@ -272,7 +275,7 @@ public static class ResultExtensions
string errorMessage = "Value is null") where T : struct =>
value.HasValue
? Result<T>.Succeed(value.Value)
: Result<T>.Fail(new ArgumentNullException(errorMessage));
: Result<T>.Fail(new ArgumentNullException(nameof(value), errorMessage));
#endregion
}

View File

@ -101,11 +101,17 @@ public readonly struct Result<A> : IEquatable<Result<A>>, IComparable<Result<A>>
public bool IsBottom => _state == ResultState.Bottom;
/// <summary>
/// 获取内部异常,若为 Bottom 状态则抛出 InvalidOperationException
/// 获取内部异常:
/// - 若为 Failure 状态,则返回内部异常
/// - 若为 Bottom 状态,则返回带有 "Result is in Bottom state." 消息的 InvalidOperationException
/// - 若为 Success 状态,则返回带有 "Cannot access Exception on a successful Result." 消息的 InvalidOperationException
/// </summary>
[Pure]
public Exception Exception => _exception
?? new InvalidOperationException("Result is in Bottom state.");
?? (IsBottom
? new InvalidOperationException("Result is in Bottom state.")
: new InvalidOperationException(
"Cannot access Exception on a successful Result."));
// ------------------------------------------------------------------ 取值
@ -266,6 +272,7 @@ public readonly struct Result<A> : IEquatable<Result<A>>, IComparable<Result<A>>
/// <returns>执行结果</returns>
public static Result<A> Try(Func<A> f)
{
ArgumentNullException.ThrowIfNull(f);
try
{
return new Result<A>(f());