From d50e84cbbd7f5d8742e5ab1794b5d050770b2d40 Mon Sep 17 00:00:00 2001 From: Sanchime Date: Sun, 8 May 2022 17:06:05 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E4=BA=86Option=E7=9A=84?= =?UTF-8?q?=E4=B8=80=E4=BA=9B=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sanchime.Test/Program.cs | 43 ++++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/Sanchime.Test/Program.cs b/Sanchime.Test/Program.cs index f5e058a..9109a88 100644 --- a/Sanchime.Test/Program.cs +++ b/Sanchime.Test/Program.cs @@ -8,12 +8,43 @@ using Sanchime.Toolkits; // Console.WriteLine(test.Value); -foo(10); -foo(Option.None); +// foo(10); +// foo(Option.None); -void foo(Option option) +// void foo(Option option) +// { +// var res = option.Map(x => x + 2); +// res.WriteLine(); +// } + +// 测试Option的Bind +var parse = (string s) => Int32.TryParse(s, out int i) ? Option.Some(i) : Option.None; +var foo = (string s) => s.Pipe(parse).Bind(Age.Of); + +foo("111").WriteLine(); +foo("aaa").WriteLine(); +foo("123").WriteLine(); +// 管道 +foo("1ab").Pipe(x => Console.WriteLine(x)); +public struct Age { - var res = option.Map(x => x + 2); - res.WriteLine(); -} + private int _value; + public static Option Of(int age) + => IsValid(age) ? Option.Some(new Age(age)) : Option.None; + + private Age(int age) + { + if (!IsValid(age)) + { + throw new ArgumentException("输入的年龄是无效的"); + } + _value = age; + } + + private static bool IsValid(int age) + => age is (>= 0 and <= 150); + + public override string ToString() + => _value.ToString(); +}