例如:
dynamic expando = new Expando();expando.name = "John Doe";var maybe = Maybe.Defer(()=>(string)expando.NonExistingProperty);//In this context I would like the exception which is thrown //to result in Maybe<string>.Novalue;if(maybe.HasValue) { //Do something}
这是否可能实现可能就是那里
解决方法 有几种方法可以使用iSynaptic.Commons来允许异常.我找到的每种方式都需要.Catch()扩展方法让monad知道以静默方式捕获异常.此外,访问该属性时要小心.值.如果此属性为Maybe.Novalue,则将抛出InvalIDOperationException.1)创建“OnExceptionNovalue”扩展方法.这将检查Maybe以查看它是否有异常.如果是,则返回Novalue Maybe.否则将返回原来的Maybe.
public static class MaybeLocalExtensions{ public static Maybe<T> OnExceptionNovalue<T>(this Maybe<T> maybe) { return maybe.Exception != null ? Maybe<T>.Novalue : maybe; }}// Sample Use Case:var maybe = Maybe.Defer(() => (string)expando.NonExistingProperty).Catch() .OnExceptionNovalue();
2)创建“BindCatch”扩展方法.当存在异常以返回Maybe.Novalue而不是抛出异常时,这会更改正常绑定的行为.
public static class MaybeLocalExtensions{ public static Maybe<TResult> BindCatch<T,TResult>(this Maybe<T> @this,Func<T,Maybe<TResult>> selector) { var self = @this; return new Maybe<TResult>(() => { if (self.Exception != null) return Maybe<TResult>.Novalue; return self.HasValue ? selector(self.Value) : Maybe<TResult>.Novalue; }); }}// Sample Use Case:var maybe = Maybe.Defer(() => (string)expando.NonExistingProperty).Catch() .BindCatch(m => m.ToMaybe());
3)这种方式也使用Catch()扩展方法,但使用maybe.HasValue属性而不是依赖于扩展方法.如果Maybe中存在异常,则HasValue属性为false.当此值为false时,Maybe.Novalue可以替换变量的值,也可以替换在这种情况下需要执行的任何 *** 作.
dynamic expando = new ExpandoObject();expando.name = "John Doe";// This example falls to the else block.var maybe = Maybe.Defer(() => (string)expando.NonExistingProperty).Catch();//In this context I would like the exception which is thrown //to result in Maybe<string>.Novalue;if (maybe.HasValue) { //Do something Console.Writeline(maybe.Value);} else { maybe = Maybe<string>.Novalue; // This line is run}// This example uses the if block.maybe = Maybe.Defer(() => (string)expando.name).Catch();//to result in Maybe<string>.Novalue;if (maybe.HasValue) { //Do something Console.Writeline(maybe.Value); //This line is run} else { maybe = Maybe<string>.Novalue;}
这些答案都是同一主题的变体,但我希望它们有所帮助.
总结以上是内存溢出为你收集整理的c# – iSynaptic.Commons和Maybe Monad全部内容,希望文章能够帮你解决c# – iSynaptic.Commons和Maybe Monad所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)