[英]Is there a .NET equivalent of Scala's Try?
我參加了Coursera反應式編程課程,並注意到了兩者之間的相似之處
在課程中,Erik Meijer畫了一張與此類似的桌子
Sync | Async
Single | Try | Future
Multiple | Iterable | Observable
盡管其余的在.NET中具有相同或相似的構造,但我找不到任何嘗試。 是否存在類似的東西?
沒有內置任何內容,因此您必須自己編寫。 基於Scala Try
我會做出類似的事情:
public interface ITry<T> : IEnumerable<T>
{
T Value { get; }
ITry<U> SelectMany<U>(Func<T, ITry<U>> bindFunc);
bool IsSuccess { get; }
}
public class FailedTry<T> : ITry<T>
{
private readonly Exception ex;
public FailedTry(Exception ex)
{
this.ex = ex;
}
public T Value
{
get { throw new InvalidOperationException("Can't get value for failed Try"); }
}
public ITry<U> SelectMany<U>(Func<T, ITry<U>> bindFunc)
{
return new FailedTry<U>(this.ex);
}
public bool IsSuccess
{
get { return false; }
}
public IEnumerator<T> GetEnumerator()
{
yield break;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public class SuccessTry<T> : ITry<T>
{
public SuccessTry(T value)
{
this.Value = value;
}
public T Value { get; private set; }
public ITry<U> SelectMany<U>(Func<T, ITry<U>> bindFunc)
{
if (bindFunc == null) return new FailedTry<U>(new ArgumentNullException("bindFunc"));
try
{
return bindFunc(this.Value);
}
catch (Exception ex)
{
return new FailedTry<U>(ex);
}
}
public bool IsSuccess
{
get { return true; }
}
public IEnumerator<T> GetEnumerator()
{
yield return this.Value;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public static class Try
{
public static ITry<T> Failed<T>(Exception ex)
{
return new FailedTry<T>(ex);
}
public static ITry<T> Create<T>(Func<T> create)
{
if (create == null) return new FailedTry<T>(new ArgumentNullException("create"));
try
{
return new SuccessTry<T>(create());
}
catch (Exception ex)
{
return new FailedTry<T>(ex);
}
}
public static ITry<U> Select<T, U>(this ITry<T> @try, Func<T, U> mapFunc)
{
return @try.SelectMany(v => Create(() => mapFunc(v)));
}
}
是這樣嗎
public class Try<TResult>
{
private readonly bool failure;
private readonly TResult result;
private readonly Exception exception;
protected Try(TResult result)
{
this.result = result;
}
protected Try(Exception ex)
{
this.exception = ex;
this.failure = true;
}
public TResult Result
{
get
{
if (this.failure) throw new InvalidOperationException();
return this.result;
}
}
public Exception Exception
{
get
{
if (!this.failure) throw new InvalidOperationException();
this.exception;
}
}
public bool Failure
{
get
{
return this.failure;
}
}
public static Try<TResult> Invoke(Func<TResult> func)
{
TResult result;
try
{
result = func();
return new Try(result);
}
catch (Exception ex)
{
return new Try(ex);
}
}
public static IEnumerable<Try<TResult>> Invoke(
IEnumerable<Func<TResult>> funcs)
{
return funcs.Select(Invoke);
}
}
您顯然必須重載Invoke
才能接受所需的類型化委托的范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.