以最近设计的订单状态的字段为例,字段类型为enum肯定是最佳的,用int,或string给维护带来不便。
而考虑到减小目前系统中的变动,最终把实体改成这样:
//只写,写的时候加个ToString()写入就行了
public string Status
{
set { _status = value; }
}
//只读
public OrderStatus TheStatus
{
get { return (OrderStatus)Enum.Parse(typeof((OrderStatus),_status,true)); }
}
顺便附上C#中enum,int,string的互相转换
public class MessageTypeConvertor
{
public static MessageType String2MessageType(string text, bool ignoreCase)
{
return (MessageType)Enum.Parse(typeof(MessageType), text, ignoreCase);
}
public static int MessageType2Int(MessageType type)
{
return (int)MessageType.SystemNormal;
}
public static MessageType Int2MessageType(int n)
{
if (Enum.IsDefined(typeof(MessageType), n))
return (MessageType)n;
else
throw new Exception(n + " is not defined");
}
public static String MessageType2String(MessageType type)
{
return MessageType.SystemNormal.ToString();
}
}
而考虑到减小目前系统中的变动,最终把实体改成这样:
//只写,写的时候加个ToString()写入就行了
public string Status
{
set { _status = value; }
}
//只读
public OrderStatus TheStatus
{
get { return (OrderStatus)Enum.Parse(typeof((OrderStatus),_status,true)); }
}
顺便附上C#中enum,int,string的互相转换
public class MessageTypeConvertor
{
public static MessageType String2MessageType(string text, bool ignoreCase)
{
return (MessageType)Enum.Parse(typeof(MessageType), text, ignoreCase);
}
public static int MessageType2Int(MessageType type)
{
return (int)MessageType.SystemNormal;
}
public static MessageType Int2MessageType(int n)
{
if (Enum.IsDefined(typeof(MessageType), n))
return (MessageType)n;
else
throw new Exception(n + " is not defined");
}
public static String MessageType2String(MessageType type)
{
return MessageType.SystemNormal.ToString();
}
}
订单状态字段优化
本文讨论了在软件开发中使用枚举(enum)类型作为订单状态字段的优势,并提供了C#中枚举与字符串及整数互相转换的方法。通过枚举类型可以减少系统维护成本,提高代码的可读性和可维护性。
2029

被折叠的 条评论
为什么被折叠?



