using Sanchime.Functional.Products; using Sanchime.Functional.Extensions; using Sanchime.Toolkits; try { void foo(Option option) { var res = option.Map(x => x + 2); res.WriteLine(); } "预计打印Some(12)".WriteLine(); foo(10); "预计打印None".WriteLine(); foo(Optional.None); "预计打印Some(String)".WriteLine(); Optional.Some(1) .Map(x => x + 1.2) .Map(x => x.ToString()) .Map(x => x.GetType().Name) .WriteLine(); // 测试Option的Bind var parse = (string s) => Int32.TryParse(s, out int i) ? Optional.Some(i) : Optional.None; var foo1 = (string s) => s.Pipe(parse).Bind(Age.Of); "预计打印Some(111)".WriteLine(); foo1("111").WriteLine(); "预计打印None".WriteLine(); foo1("aaa").WriteLine(); "预计打印Some(123)".WriteLine(); foo1("123").WriteLine(); // 管道 "预计打印None".WriteLine(); foo1("1ab").Pipe(x => x.WriteLine()); } catch (Exception ex) { ex.Message.WriteLine(); ex.StackTrace.WriteLine(); } public struct Age { private int _value; public static Option Of(int age) => IsValid(age) ? Optional.Some(new Age(age)) : Optional.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(); }