• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
皇图霸业谈笑间
更高、更快、更强
博客园    首页    新随笔    联系   管理    订阅  订阅
谈谈枚举的其他用法

一、 组合枚举(也就是我们常说的flags)

 

组合枚举有个flags 特性, 就是给枚举标记上 [Flags], 当然你只要设置好组合枚举的位值, 不标记这个东西也是可以正常在业务里面使用的,那我们就看看有没有标记这个特性,他们有什么区别:

A: 使用system.flagsattributes定制特性,使得tostring或format方法可以查找枚举数值中的每个匹配符号,将它们连接为一个字符串,并用逗号分开;parse方法可用该特性拆分字符串并得到复合的枚举类型

B: 使用格式字符串f或f 也有同样的效果

代码举例说明:

using system;
[flags] //定制特性
public enum human : byte //定制基本类型
{
male = 0x01,
female = 0x10
}

public class enumtest
{
public static void main()
{
human human = human.male | human.female;
console.writeline(human.tostring()); //使用flags定制特性的情况
//console.writeline(human.tostring("f")); //没有使用flags定制特性的情况

console.writeline(enum.format(typeof(human), human, "g"));//使用flags定制特性的情况
//console.writeline(enum.format(typeof(human), human, "f"));//没有使用flags定制特性的情况

human = (human)enum.parse(typeof(human), "17");
console.writeline(human.tostring()); //使用flags定制特性的情况
//console.writeline(human.tostring("f")); //没有使用flags定制特性的情况
}
}

 

执行结果:

/*运行结果

male, female

male, female

male, female

*/ 

 

从上面的执行结果我们可以看到: 使用flags 特性和不使用 flags特性的区别了。

 

二、枚举本地化:(本质上枚举属硬编码,只是看起来没有那么丑陋)

我们很聪明的将业务中比较经常发生变化的信息,用枚举进行抽象,从此以为走上了应对变化的设计之路。但是当我们发现用户不断提出对枚举变量更多变化的时候,我们还是时不时要通过修改代码的方式重新编译执行。这就让枚举的设计显得有点不雅,于是枚举的本地化理念就孕育而生了,下面我们来看下如何将枚举本地化。

利用.NET的泛型机制:

/// <summary>
 /// 本地化枚举通用方法
 /// </summary>
 /// <returns></returns>
 /// <author>Ryanding</author>
  private static string LocalizeEnumeration(object enumerator)
 {

     ResourceManager resources = new ResourceManager("resx文件名",
		 System.Reflection.Assembly.GetExecutingAssembly());

     string name = String.Format("{0}.{1}.Text", enumerator.GetType().Name, enumerator);
     string localizedDescription = resources.GetString(name);

     if (localizedDescription == null)
	 return enumerator.ToString();
     else
	 return localizedDescription;
 }

 /// <summary>
 /// 翻译枚举成中文
 /// </summary>
  public static List<KeyValuePair> GetEnumStringList<T>()
 {
     string[] resultPrepare = Enum.GetNames(typeof(T));

     List<KeyValuePair> result = new List<KeyValuePair>();
     Array.ForEach(resultPrepare, f => result.Add(new KeyValuePair
     {
	 Key = (int)(Enum.Parse(typeof(T), f)),
	 Value = LocalizeEnumeration(Enum.Parse(typeof(T), f))
     }
     ));

     return result;
 }

 

 

 

 
posted on 2013-11-27 11:40  布颜书  阅读(247)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3