ASP.Net Core中使用枚举类而不是枚举的方法
前言:
我相信大家在编写代码时经常会遇到各种状态值,而且为了避免硬编码和代码中出现魔法数,通常我们都会定义一个枚举,来表示各种状态值,直到我看到java中这样使用枚举,我再想c# 中可不可以这样写,今天就分享一下我的感悟。
一、通常我们是这样使用枚举的
(1)switch中使用枚举
public enum employeetype { manager, servant, assistanttotheregionalmanager }
public class employee { public employeetype type { get; set; } public decimal bonus { get; set; } }
static void processbonus(employee employee) { switch (employee.type) { case employeetype.manager: employee.bonus = 1000m; break; case employeetype.servant: employee.bonus = 0.01m; break; case employeetype.assistanttotheregionalmanager: employee.bonus = 1.0m; break; default: throw new argumentoutofrangeexception(); } }
在没有进某唐时我也是这样的写的,代码很烂,违法了开闭原则,扩展性极差。在代码规范中是不允许出现这样的写法的。对于上面的写法可以使用设计模式来重构。后面会继续更新设计模式的文章。
(2)类型转换
enumtricks.isvolumehigh((volume)27); enumtricks.high((int)medium);
二、枚举的不好之处
关于枚举的msdn文档说了什么:
“the enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. every enumeration type has an underlying type, which can be any integral type except char. the default underlying type of the enumeration elements is int. by default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1.
(1)没有类型安全
枚举是简单的值类型,可以提供对无效值的保护,并且不会出现任何行为。他们是有用的,因为他们是魔法数字的改进,但就是这样。如果要约束类型可能的值,枚举不一定能帮助您,因为仍然可以提供无效类型。例如,此枚举有三个值,默认情况下将具有int类型。值范围为1到3。
public enum volume { low = 1, medium, high }
public static class enumtricks { public static bool isvolumehigh(volume volume) { var result = false; switch (volume) { case volume.low: console.writeline("volume is low."); break; case volume.medium: console.writeline("volume is medium."); break; case volume.high: console.writeline("volume is high."); result = true; break; } return result; } }
static void main(string[] args) { enumtricks.isvolumehigh((volume)27); console.readkey(); }
public static class enumtricks { public static bool isvolumehigh(volume volume) { var result = false; switch (volume) { case volume.low: console.writeline("volume is low."); break; case volume.medium: console.writeline("volume is medium."); break; case volume.high: console.writeline("volume is high."); result = true; break; } return result; } public static int enumtoint(volume volume) { return (int)volume; } public static volume inttoenum(int intvalue) { return (volume)intvalue; } public static volume stringtoenum(string stringvalue) { return (volume)enum.parse(typeof(volume), stringvalue); } public static int stringtoint(string stringvalue) { var volume = stringtoenum(stringvalue); return enumtoint(volume); } public static string enumtostring(volume volume) { return volume.tostring(); } }
这应该失败,至少在运行时。它没有。这真的很奇怪......在编译期间或运行期间都不会检测到错误的调用。你会觉得自己处于一个虚假的安全状态。如果,我们把传进去的枚举转换为string时,来看看这两种情况有什么不同:
我不知道大家平时在使用枚举的时候,是否有意识检查传入的是否是有效的值。可以使用enum.isdefined()
来检查int值是否是一个有效的值
解决方案:如果int值在枚举值的定义范围内,则使用enum.isdefined()
查找。如果在范围内,则返回true,否则返回false。
(2)转化
您是否尝试过将enum转换为int,int转换为enum,string转换为enum,将字符串转换为enum的int值?如下代码:
public static class enumtricks { public static bool isvolumehigh(volume volume) { var result = false; switch (volume) { case volume.low: console.writeline("volume is low."); break; case volume.medium: console.writeline("volume is medium."); break; case volume.high: console.writeline("volume is high."); result = true; break; } return result; } public static int enumtoint(volume volume) { return (int)volume; } public static volume inttoenum(int intvalue) { return (volume)intvalue; } public static volume stringtoenum(string stringvalue) { return (volume)enum.parse(typeof(volume), stringvalue); } public static int stringtoint(string stringvalue) { var volume = stringtoenum(stringvalue); return enumtoint(volume); } }
是不是我们日常的代码中也有这样的类型转换代码,不是说不好,只是类型转换也是有性能损失的,如果能换中方式可以同样实现而且还避免以上问题岂不是更好,这样我们的代码也更好维护和扩展,下面我们通过使用枚举类的方式来解决这个问题。
三、使用枚举类而不是枚举类型
public class enumeration: icomparable { private readonly int _value; private readonly string _displayname; protected enumeration() { } protected enumeration(int value, string displayname) { _value = value; _displayname = displayname; } public int value { get { return _value; } } public string displayname { get { return _displayname; } } public override string tostring() { return displayname; } public static ienumerable<t> getall<t>() where t : enumeration, new() { var type = typeof(t); var fields = type.getfields(bindingflags.public | bindingflags.static | bindingflags.declaredonly); foreach (var info in fields) { var instance = new t(); var locatedvalue = info.getvalue(instance) as t; if (locatedvalue != null) { yield return locatedvalue; } } } public override bool equals(object obj) { var othervalue = obj as enumeration; if (othervalue == null) { return false; } var typematches = gettype().equals(obj.gettype()); var valuematches = _value.equals(othervalue.value); return typematches && valuematches; } public override int gethashcode() { return _value.gethashcode(); } public static int absolutedifference(enumeration firstvalue, enumeration secondvalue) { var absolutedifference = math.abs(firstvalue.value - secondvalue.value); return absolutedifference; } public static t fromvalue<t>(int value) where t : enumeration, new() { var matchingitem = parse<t, int>(value, "value", item => item.value == value); return matchingitem; } public static t fromdisplayname<t>(string displayname) where t : enumeration, new() { var matchingitem = parse<t, string>(displayname, "display name", item => item.displayname == displayname); return matchingitem; } private static t parse<t, k>(k value, string description, func<t, bool> predicate) where t : enumeration, new() { var matchingitem = getall<t>().firstordefault(predicate); if (matchingitem == null) { var message = string.format("'{0}' is not a valid {1} in {2}", value, description, typeof(t)); throw new applicationexception(message); } return matchingitem; } public int compareto(object other) { return value.compareto(((enumeration)other).value); } }
public class volume: enumeration { private volume() { throw new exception(""); } private volume(int value, string displayname): base(value, displayname) { } public static readonly volume low = new volume(1, nameof(low).tolowerinvariant()); public static readonly volume medium = new volume(2, nameof(medium).tolowerinvariant()); public static readonly volume high = new volume(3, nameof(high).tolowerinvariant()); public static ienumerable<volume> list() => new[] { low, medium, high }; public static volume from(int value) { var state = list().singleordefault(s => s.value == value); if (state == null) { throw new exception($"possible values for volume: {string.join(",", list().select(s => s.value))}"); } return state; } public static volume fromname(string name) { var state = list() .singleordefault(s => string.equals(s.displayname, name, stringcomparison.currentcultureignorecase)); if (state == null) { throw new exception($"possible values for volume: {string.join(",", list().select(s => s.displayname))}"); } return state; } }
static void main(string[] args) { //enumtricks.isvolumehigh((volume)27); //var tmp = enum.isdefined(typeof(volume), 3); //var str = enumtricks.enumtostring((volume)27); //var str2 = enumtricks.enumtostring((volume)3); //console.writeline($"volume 27:{str}"); //console.writeline($"volume 3:{str2}"); console.writeline("------------------------------------------------------------"); console.writeline(volume.high.value); console.writeline(volume.high.displayname); var volume = volume.from(2); var volume2 = volume.fromname("high"); var none = volume.from(27); console.readkey(); }
四、应用
代码如下:
error文件下:
public interface icommonerror { int geterrcode(); string geterrmsg(); icommonerror seterrmsg(string errmsg); }
public class enumeration : icomparable { private readonly int _value; private readonly string _displayname; protected enumeration() { } protected enumeration(int value, string displayname) { _value = value; _displayname = displayname; } public int value { get { return _value; } } public string displayname { get { return _displayname; } } public override string tostring() { return displayname; } public static ienumerable<t> getall<t>() where t : enumeration, new() { var type = typeof(t); var fields = type.getfields(bindingflags.public | bindingflags.static | bindingflags.declaredonly); foreach (var info in fields) { var instance = new t(); var locatedvalue = info.getvalue(instance) as t; if (locatedvalue != null) { yield return locatedvalue; } } } public override bool equals(object obj) { var othervalue = obj as enumeration; if (othervalue == null) { return false; } var typematches = gettype().equals(obj.gettype()); var valuematches = _value.equals(othervalue.value); return typematches && valuematches; } public override int gethashcode() { return _value.gethashcode(); } public static int absolutedifference(enumeration firstvalue, enumeration secondvalue) { var absolutedifference = math.abs(firstvalue.value - secondvalue.value); return absolutedifference; } public static t fromvalue<t>(int value) where t : enumeration, new() { var matchingitem = parse<t, int>(value, "value", item => item.value == value); return matchingitem; } public static t fromdisplayname<t>(string displayname) where t : enumeration, new() { var matchingitem = parse<t, string>(displayname, "display name", item => item.displayname == displayname); return matchingitem; } private static t parse<t, k>(k value, string description, func<t, bool> predicate) where t : enumeration, new() { var matchingitem = getall<t>().firstordefault(predicate); if (matchingitem == null) { var message = string.format("'{0}' is not a valid {1} in {2}", value, description, typeof(t)); throw new applicationexception(message); } return matchingitem; } public int compareto(object other) { return value.compareto(((enumeration)other).value); } }
public class embusinesserror : enumeration, icommonerror { private int errcode; private string errmsg; public static readonly embusinesserror parametervalidationerror = new embusinesserror(10001, "参数不合法"); private embusinesserror() { throw new exception("私有构造函数不能调用"); } private embusinesserror(int value, string displayname) : base(value, displayname) { this.errcode = value; this.errmsg = displayname; } public int geterrcode() { return this.errcode; } public string geterrmsg() { return this.errmsg; } public void seterrcode(int errcode) { this.errcode = errcode; } public icommonerror seterrmsg(string errmsg) { this.errmsg = errmsg; return this; } }
//包装器业务异常类实现 public class businessexception : exception, icommonerror { private icommonerror commonerror; //直接接收embusinesserror的传参用于构造业务异常 public businessexception(icommonerror commonerror):base() { this.commonerror = commonerror; } public businessexception(icommonerror commonerror, string errmsg):base() { this.commonerror = commonerror; this.commonerror.seterrmsg(errmsg); } public int geterrcode() { return this.commonerror.geterrcode(); } public string geterrmsg() { return this.commonerror.geterrmsg(); } public icommonerror seterrmsg(string errmsg) { this.commonerror.seterrmsg(errmsg); return this; } public icommonerror getcommonerror() { return commonerror; } }
异常中间件:
public class exceptionhandlermiddleware { private readonly requestdelegate next; /// <summary> /// /// </summary> /// <param name="next"></param> public exceptionhandlermiddleware(requestdelegate next) { this.next = next; } public async task invoke(httpcontext context) { try { await next(context); } catch (exception ex) { await handleexceptionasync(context, ex); } } private static async task handleexceptionasync(httpcontext context, exception exception) { if (exception == null) return; await writeexceptionasync(context, exception).configureawait(false); } private static async task writeexceptionasync(httpcontext context, exception exception) { var response = context.response; response.contenttype = "application/json;charset=utf-8"; var result = new commonreturntype(); if (exception is businessexception) { var businessexception = (businessexception)exception; var errmodel = new { errcode= businessexception.geterrcode(), errmsg= businessexception.geterrmsg() }; result = commonreturntype.create(errmodel, "fail"); } await response.writeasync(jsonconvert.serializeobject(new { data = result.getdata(), status = result.getstatus() }) ).configureawait(false); } }
response文件夹:
public class commonreturntype { //表明对应请求的返回处理结果 "success" 或 "fail" private string status; //若status=success,则data内返回前端需要的json数据 //若status=fail,则data内使用通用的错误码格式 private object data; //定义一个通用的创建方法 public static commonreturntype create(object result) { return commonreturntype.create(result, "success"); } public static commonreturntype create(object result, string status) { commonreturntype type = new commonreturntype(); type.setstatus(status); type.setdata(result); return type; } public string getstatus() { return status; } public void setstatus(string status) { this.status = status; } public object getdata() { return data; } public void setdata(object data) { this.data = data; } }
最后推荐一个类库,这是我在nuget上发现的枚举类库,地址:https://github.com/ardalis/smartenum
好了,先分享到这里,希望对你有帮助和启发。
参考资料:
(1)
(2)
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。
上一篇: C#实现求一组数据众数的方法