From 537b7280de70bdcf8641648378300a46d77a9dbd Mon Sep 17 00:00:00 2001 From: Sanchime Date: Sun, 8 May 2022 21:33:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0Option=E8=BD=AC=E6=8D=A2?= =?UTF-8?q?=E5=88=B0Either=E7=9A=84=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sanchime.Functional/Core/Extensions/Option.cs | 11 +++++++++++ Sanchime.Functional/Core/Products/Option.cs | 15 +++++++++++---- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/Sanchime.Functional/Core/Extensions/Option.cs b/Sanchime.Functional/Core/Extensions/Option.cs index d86d631..6805789 100644 --- a/Sanchime.Functional/Core/Extensions/Option.cs +++ b/Sanchime.Functional/Core/Extensions/Option.cs @@ -96,6 +96,17 @@ public static class OptionExtension public static Option OrElse(this Option left, Func> right) => left.Match(() => right(), (_) => left); + /// + /// 将 + /// + /// + /// + /// + /// + /// + public static Either ToEither(this Option option, R error) + => option.IsSome() ? Either.Right(error) : Either.Left(option.Value); + #region Linq式 public static Option Select(this Option source, Func mapping) diff --git a/Sanchime.Functional/Core/Products/Option.cs b/Sanchime.Functional/Core/Products/Option.cs index e33f560..f332c95 100644 --- a/Sanchime.Functional/Core/Products/Option.cs +++ b/Sanchime.Functional/Core/Products/Option.cs @@ -26,7 +26,6 @@ public static class Option public readonly struct Option : IEquatable, IEquatable> { - private readonly TValue _value; private readonly bool _isSome; @@ -57,11 +56,19 @@ public readonly struct Option : IEquatable, IEquatable(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); + /// + /// 获取内部的值,如果为则抛出异常 + /// + /// + public TValue ValueUnsafe => this.Match(() => throw new InvalidOperationException(), val => val); + /// + /// 获取内部的值,如果为则返回默认值 + /// + /// + public TValue Value => this.Match(() => default!, val => val); /// /// 转换为序列