是否有与 Scala 的 Try 等效的 .NET 版本?

Jim*_*ies 3 .net c# scala

我一直在参加 Coursera 响应式编程课程,并注意到两者之间的相似之处

  1. .NET 任务和 Scala Future
  2. 可观察到的数据显然非常相似
  3. .NET IEnumerable 和 Scala Iterable

在课程中 Erik Meijer 绘制了一个与此类似的表格

           Sync     | Async
Single   | Try      | Future
Multiple | Iterable | Observable
Run Code Online (Sandbox Code Playgroud)

虽然其余的在 .NET 中具有等效或类似的构造,但我找不到类似 try 的东西。是否存在类似的东西?

Lee*_*Lee 5

没有内置任何内容,因此您必须自己编写。基于 ScalaTry我会做类似的事情:

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)));
    }
}
Run Code Online (Sandbox Code Playgroud)