这段时间手里有个有关订单的项目,订单一般有个状态的,以前很多要时候都会想到订单的状态就那几个种,就把它写死吧,不用一个数据库表了,太浪费资源了,但写死了用一个数字来代表一种订单状态,这样在编码时还要记得什么数字代码什么状态,如果不小心把它写错了,会导致数据出错。
后来想到.NET有个枚举,这么好的东西为何不用上来呢,这不但可以方便以后的代码维护,也方便编码。
利用switch case
后来想到.NET有个枚举,这么好的东西为何不用上来呢,这不但可以方便以后的代码维护,也方便编码。
public enum OrderState
{
/// <summary>
/// 无效状态
/// </summary>
Invalid = 0,
/// <summary>
/// 客户询价
/// </summary>
CustomerQuery = 1,
/// <summary>
/// 客户落单
/// </summary>
CustomerOrdered = 2,
/// <summary>
/// 客户付款
/// </summary>
ReceiverCustomerPayment = 4,
/// <summary>
/// 向供货商订货
/// </summary>
SupplierOrdered = 8,
/// <summary>
/// 供货商确认货期
/// </summary>
SupplierOrderTerm = 16,
/// <summary>
/// 收到货品
/// </summary>
RecieverGoods = 32,
/// <summary>
/// 客户取消订单
/// </summary>
CustomerCanceled = 64,
/// <summary>
/// 供货商取消订单
/// </summary>
SupplierCancelded = 128
}
但要从UI层看这些状态怎么处理呢?{
/// <summary>
/// 无效状态
/// </summary>
Invalid = 0,
/// <summary>
/// 客户询价
/// </summary>
CustomerQuery = 1,
/// <summary>
/// 客户落单
/// </summary>
CustomerOrdered = 2,
/// <summary>
/// 客户付款
/// </summary>
ReceiverCustomerPayment = 4,
/// <summary>
/// 向供货商订货
/// </summary>
SupplierOrdered = 8,
/// <summary>
/// 供货商确认货期
/// </summary>
SupplierOrderTerm = 16,
/// <summary>
/// 收到货品
/// </summary>
RecieverGoods = 32,
/// <summary>
/// 客户取消订单
/// </summary>
CustomerCanceled = 64,
/// <summary>
/// 供货商取消订单
/// </summary>
SupplierCancelded = 128
}
利用switch case
public static string GetOrderStateString(OrderState state)
{
switch (state)
{
case OrderState.Invalid:
return "无效值";
case OrderState.CustomerOrdered:
return "客户下单";
case OrderState.CustomerCanceled:
return "客户取消订单";
case OrderState.CustomerQuery:
return "客户询价";
case OrderState.ReceiverCustomerPayment:
return "客户已付款";
case OrderState.RecieverGoods:
return "订单到货";
case OrderState.SupplierCancelded:
return "供货商取消";
case OrderState.SupplierOrdered:
return "已向供货商订货";
case OrderState.SupplierOrderTerm:
return "供货商确认货期";
}
return "";
}
{
switch (state)
{
case OrderState.Invalid:
return "无效值";
case OrderState.CustomerOrdered:
return "客户下单";
case OrderState.CustomerCanceled:
return "客户取消订单";
case OrderState.CustomerQuery:
return "客户询价";
case OrderState.ReceiverCustomerPayment:
return "客户已付款";
case OrderState.RecieverGoods:
return "订单到货";
case OrderState.SupplierCancelded:
return "供货商取消";
case OrderState.SupplierOrdered:
return "已向供货商订货";
case OrderState.SupplierOrderTerm:
return "供货商确认货期";
}
return "";
}
如果以后还有更多的订单状态就修改这个枚举和一个方法就行了,这么方便的东西为何就不用到我的程序中呢,我们在编码中,要想尽方法使代码简单、易用、易维护。
枚举中有两个很实用的方法
1、GetHashCode() //返回该实例的值的哈希代码
2、ToString() //将此实例的值转换为其等效的字符串表示
这两个方法在编码的时候会用到,GetHashCode()这个方法使用机会会更多。
有前枚举的使用,我得出以上一点心得,与大家共享一下。