我有一个IResult<T>用于处理错误的容器。它看起来像这样:
public interface IResult<out T>
{
ResultOutcome Outcome { get; } //enum: {Failure, Uncertain, Success}
string Description { get; } //string describing the error, in case of !Success
bool IsSuccess(); //Outcome == Success
T Data { get; } //If success, it contains the data passed on, otherwise NULL
}
Run Code Online (Sandbox Code Playgroud)
你会像这样使用它:
IResult<int> GetSomething()
{
try{
int result = //things that might throw...
return Result<int>.Success(result);
}
catch(Exception e)
{
return Result<int>.Failure($"Something went wrong: {e.Message}");
}
}
Run Code Online (Sandbox Code Playgroud)
进而:
var result = …Run Code Online (Sandbox Code Playgroud)