C# 如何定义一个带泛型属性的返回类型类 ,用来做统一的后端数据返回格式
一、简单诉求:
1、请求成功、失败标识:Code
2、请求结果说明:Message
3、返回数据:Data
二、简单诉求分析:
1、诉求前两条没什么好说的
2、针对诉求3,实际上需要根据不同的返回数据才能确定数据类型,因此我们想到采用泛型
三、话不多说,直接上代码
CommonServiceResponse.cs
using System; namespace Awing.IBMS.MyServiceResponse { /// <summary> /// 数据类型转换 data.ToCommonServiceResponse("成功!") /// </summary> public static class CommonServiceResponseEX { public static CommonServiceResponse<T> ToCommonServiceResponse<T>(this T data,string message="") where T:class { return CommonServiceResponse<T>.Success(message, data); } } /// <summary> /// 返回类 /// </summary> /// <typeparam name="T"></typeparam> public class CommonServiceResponse<T> where T :class { public MyResponseCode Code { get; set; } public string Message { get; set; } //返回数据 public T Data { get; set; } /// <summary> /// 成功 /// </summary> /// <param name="message"></param> /// <param name="data"></param> /// <returns></returns> public static CommonServiceResponse<T> Success(string message, T data) { return new CommonServiceResponse<T> { Message = message, Code = MyResponseCode.Success, Data= data }; } /// <summary> /// 失败 /// </summary> /// <param name="code"></param> /// <param name="message"></param> /// <returns></returns> public static CommonServiceResponse<T> Fail( string message = "") { return new CommonServiceResponse<T> { Message = message, Code =MyResponseCode.Failed }; } } }
然后发下自己想复杂了,实际我不需要在乎数据是什么类型的,他是什么类型我就返回什么类型即可,采用object和dynamic。
using System; namespace Awing.IBMS.MyServiceResponse { /// <summary> /// 数据类型转换 data.ToCommonServiceResponse("成功!") /// </summary> public static class CommonServiceResponseEX { public static CommonServiceResponse ToCommonServiceResponse(this object data,string message="") { return CommonServiceResponse.Success(message, data); } } /// <summary> /// 返回类 /// </summary> public class CommonServiceResponse { public MyResponseCode Code { get; set; } public string Message { get; set; } //返回数据 public dynamic Data { get; set; } /// <summary> /// 成功 /// </summary> /// <param name="message"></param> /// <param name="data"></param> /// <returns></returns> public static CommonServiceResponse Success(string message, dynamic data=null) { return new CommonServiceResponse { Message = message, Code = MyResponseCode.Success, Data= data }; } /// <summary> /// 失败 /// </summary> /// <param name="message"></param> /// <returns></returns> public static CommonServiceResponse Fail( string message = "") { return new CommonServiceResponse { Message = message, Code =MyResponseCode.Failed }; } } }
其中,MyServiceResponse.cs
using System;namespace Awing.IBMS.MyServiceResponse { public enum MyResponseCode { Failed = 0, Success = 20000 } }
打完收工!
斩后知