添加Option转换到Either的支持

This commit is contained in:
Sanchime 2022-05-08 21:33:25 +08:00
parent bc275bae7c
commit 537b7280de
2 changed files with 22 additions and 4 deletions

View File

@ -96,6 +96,17 @@ public static class OptionExtension
public static Option<T> OrElse<T>(this Option<T> left, Func<Option<T>> right)
=> left.Match(() => right(), (_) => left);
/// <summary>
/// 将<see cref="Option"转为<see cref="Either"/>
/// </summary>
/// <param name="option"></param>
/// <param name="error"></param>
/// <typeparam name="L"></typeparam>
/// <typeparam name="R"></typeparam>
/// <returns></returns>
public static Either<L, R> ToEither<L, R>(this Option<L> option, R error)
=> option.IsSome() ? Either.Right(error) : Either.Left(option.Value);
#region Linq式
public static Option<R> Select<T, R>(this Option<T> source, Func<T, R> mapping)

View File

@ -26,7 +26,6 @@ public static class Option
public readonly struct Option<TValue> : IEquatable<None>, IEquatable<Option<TValue>>
{
private readonly TValue _value;
private readonly bool _isSome;
@ -57,11 +56,19 @@ public readonly struct Option<TValue> : IEquatable<None>, IEquatable<Option<TVal
public static implicit operator Option<TValue>(TValue value)
=> value is null ? Option.None : Option.Some(value);
public bool IsSome() => this.Match(() => false, (_) => true);
internal bool IsSome() => this.Match(() => false, (_) => true);
internal TValue ValueUnsafe => this.Match(() => throw new InvalidOperationException(), val => val);
/// <summary>
/// 获取<see cref="Option"/>内部的值,如果为<see cref="Option.None"/>则抛出异常
/// </summary>
/// <returns></returns>
public TValue ValueUnsafe => this.Match(() => throw new InvalidOperationException(), val => val);
/// <summary>
/// 获取<see cref="Option"/>内部的值,如果为<see cref="Option.None"/>则返回默认值
/// </summary>
/// <returns></returns>
public TValue Value => this.Match(() => default!, val => val);
/// <summary>
/// 转换为序列