using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class Result { public Result() { } private int _code; private readonly string _msg; /// /// 结果是否成功 /// public bool IsSuccess => _code == 0; /// /// 结果代码 /// public int Code { set => _code = value; get => _code; } /// /// 结果消息 /// public string Msg => _msg; /// /// 构造方法 /// /// /// /// protected Result(int code, string msg, Exception? exception = null) { if (exception != null) { var listMoreMsg = new List(); if (exception is ResultException resultException) { listMoreMsg.AddRange(resultException.MessageList); } //else if (exception is DeviceControlException deviceControlException) //{ // listMoreMsg.Add(deviceControlException.ErrorInfo); //} else { listMoreMsg.Add(exception.Message); } var strMoreMsg = string.Join("、", listMoreMsg.Where(it => !string.IsNullOrWhiteSpace(it))); if (!string.IsNullOrWhiteSpace(strMoreMsg)) { msg += $"({strMoreMsg})"; } } _code = code; _msg = msg; } /// /// 返回成功结果 /// /// /// public static Result Success() { return new Result(0, ""); } /// /// 返回错误结果 /// /// /// /// public static Result Error(string msg, Exception? exception = null) { return new Result(-1, msg, exception); } } public class Result : Result { public Result() { } private T? _data; /// /// 结果数据 /// public T? Data { set => _data = value; get => _data; } /// /// 构造方法 /// /// /// /// /// private Result(int code, string msg, T? data, Exception? exception = null) : base(code, msg, exception) { _data = data; } /// /// 返回成功数据 /// /// /// public static Result Success(T data) { return new Result(0, "", data); } /// /// 返回失败信息 /// /// /// /// public new static Result Error(string msg, Exception? exception = null) { return new Result(-1, msg, default, exception); } /// /// 返回失败信息和数据 /// /// /// /// /// public static Result Error(string msg, T data, Exception? exception = null) { return new Result(-1, msg, data, exception); } } public class ResultException : Exception { private List? _messageList; public List MessageList { get { List messages = new(); if (_messageList != null) { messages.AddRange(_messageList.Where(it => !string.IsNullOrWhiteSpace(it))); } return messages; } } public override string Message => string.Join(", ", MessageList); public ResultException() : base(null) { } public void AddAdditionMessage(string message) { _messageList ??= new(); _messageList.Add(message); } } }