.net 这段C#代码从一个方法返回两种不同的对象类型?这怎么可能?

xzv2uavs  于 2023-05-01  发布在  .NET
关注(0)|答案(1)|浏览(129)

下面是some code from a video by Nick Chapsas的屏幕截图,显示该方法返回了2x个不同的对象类型。
我显示屏幕截图(而不是代码),因为我想强调他的IDE没有抱怨,看起来像是合法的:

public async Task<Result<Movie, ValidationFailed>> Handle(SomeCommand request, CT ct)
{
    var movie = new Movie();

    ....

    if (!validationResult.IsValid)
    {
        return new ValidationFailed(...);
    }

    ....
    return movie;
}

我想他的Result类是这样的:

public readonly struct Result<TValue, TError>
    {
        private readonly TValue? _value;
        private readonly TError? _error;

        public Result(TValue value)
        {
            _value = value;
            _error = default;
        }

        public Result(TError error)
        {
            _error = error;
            _value = default;
        }

        public TValue? Value => _value;
        public TError? Error => _error;
        public bool IsSuccess => Error != null;
    }

这怎么可能?
我以为他会做这样的事情:

if (!validationResult.IsValid)
    {
        return new Result(new new ValidationFailed(...));
    }

    ....
    return new Result(movie);

Movie会继承Result吗?看起来不像..

public partial class Movie
{
    ....
}

有人能帮忙吗?

tp5buhyn

tp5buhyn1#

对于这个结构体,你还需要有两个隐式运算符,如下所示:

public static implicit operator Result<TValue, TError>(TValue value) => new(value);
public static implicit operator Result<TValue, TError>(TError error) => new(error);

和一个方法来获得结果:

public TResult Match<TResult>(Func<TValue, TResult> value, Func<TError, TResult> error)
        => _value is not null ? value(_value) : error(_error);

完整代码:

public readonly struct Result<TValue, TError>
{
    private readonly TValue _value;
    private readonly TError _error;

    public bool IsError { get; }

    public Result(TValue value)
    {
        IsError = false;
        _value = value;
        _error = default;
    }

    public Result(TError error)
    {
        IsError = true;
        _value = default;
        _error = error;
    }

    public static implicit operator Result<TValue, TError>(TValue value) => new(value);
    public static implicit operator Result<TValue, TError>(TError error) => new(error);
    public TResult Match<TResult>(Func<TValue, TResult> value, Func<TError, TResult> error)
        => _value is not null ? value(_value) : error(_error);
}

相关问题