Created
November 27, 2012 15:34
-
-
Save wonderful-panda/4154848 to your computer and use it in GitHub Desktop.
chain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq; | |
| using System.Text; | |
| namespace ConsoleApplication1 | |
| { | |
| public class MyEx1 : Exception | |
| { | |
| public MyEx1(string msg, Exception inner) : base(msg, inner) { } | |
| }; | |
| public class MyEx2 : Exception | |
| { | |
| }; | |
| public static class Chain | |
| { | |
| /// <summary> | |
| /// func()の結果を返す。例外が発生したらexc()が返す例外を投げる | |
| /// </summary> | |
| public static T begin<T>(Func<T> func, Func<Exception, Exception> exc) | |
| { | |
| try | |
| { | |
| return func(); | |
| } | |
| catch (Exception ex) | |
| { | |
| throw exc(ex); | |
| } | |
| } | |
| /// <summary> | |
| /// func()の結果を返す。例外が発生したらexc()が返す例外を投げる | |
| /// </summary> | |
| public static TNext chain<T, TNext>(this T value, Func<T, TNext> func, Func<Exception, Exception> exc) | |
| { | |
| try | |
| { | |
| return func(value); | |
| } | |
| catch (Exception ex) | |
| { | |
| throw exc(ex); | |
| } | |
| } | |
| /// <summary> | |
| /// func()の結果を返す。 | |
| /// </summary> | |
| public static TNext chain<T, TNext>(this T value, Func<T, TNext> func) | |
| { | |
| return func(value); | |
| } | |
| /// <summary> | |
| /// 値をチェックして、NGならexc()が返す例外を投げる。OKならその値をそのまま返す | |
| /// </summary> | |
| public static T assert<T>(this T value, Predicate<T> pred, Func<T, Exception> exc) | |
| { | |
| if (!pred(value)) | |
| throw exc(value); | |
| else | |
| return value; | |
| } | |
| } | |
| class Program | |
| { | |
| static int ExecuteF() | |
| { | |
| return 1; | |
| } | |
| static string ExecuteG(int x) | |
| { | |
| return x.ToString(); | |
| } | |
| static int ExecuteH(string x) | |
| { | |
| return int.Parse(x); | |
| } | |
| static void Main(string[] args) | |
| { | |
| // F, G, Hを順番に実行。F、Gで例外が出たらMyEx1を、Hの結果が0ならMyEx2を投げる | |
| var value = Chain.begin(ExecuteF, | |
| ex => new MyEx1("F failed", ex)) | |
| .chain(ExecuteG, | |
| ex => new MyEx1("G failed", ex)) | |
| .chain(ExecuteH) | |
| .assert(x => x != 0, | |
| x => new MyEx2()); | |
| Console.WriteLine(value); | |
| Console.Read(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment