恰好在C#中的结构和接口之间发生装箱

时间:2016-03-09 21:14:41

标签: c#

您能否在以下代码的上下文中解释它:

interface Result<T>
{
    bool IsSuccess { get; }

    T Value { get; }

    string FailureMessage { get; }

    Result<R> Map<R>(Func<T, R> transform);
}

struct Success<T> : Result<T>
{
    private readonly T _value;

    public Success(T value)
    {
        _value = value;
    }

    public bool IsSuccess { get { return true; } }

    public T Value { get { return _value; } }

    public string FailureMessage
    {
        get
        {
            throw new InvalidOperationException("FailureMessage is invalid when IsSuccess == true");
        }
    }

    public Result<R> Map<R>(Func<T, R> transform)
    {
        return new Success<R>(transform(_value));
    }
}

struct Failure<T> : Result<T>
{
    private readonly string _failureMessage;

    public Failure(string failureMessage)
    {
        _failureMessage = failureMessage;
    }

    public bool IsSuccess { get { return false; } }

    public T Value
    {
        get
        {
            throw new InvalidOperationException("Value is invalid when IsSuccess == false");
        }
    }

    public string FailureMessage { get { return _failureMessage; } }

    public Result<R> Map<R>(Func<T, R> transform)
    {
        return new Failure<R>(_failureMessage);
    }
}

我会使用上面的代码如下:

Result<string> result = Get(url);
Result<Something> s = result.Map(v => ParseIntoSomething(v));
if (s.IsSuccess)
{
    DoSomethingWith(s.Value);
}
else
{
    ReportFailure(s.FailureMessage);
}

我怀疑只要将Get()的结果分配给Result<string>类型的变量,就会发生装箱。这是否意味着在这种情况下使用结构的想法是毫无意义的?

0 个答案:

没有答案