- 总结C#枚举在开发项目中的应用
- http://developer.51cto.com 2010-12-08 09:38 RyanDing 博客园 我要评论(0)
- 今天我们谈到的是在实际项目中对C#枚举的应用总结,如果存在不足的地方欢迎大家指出。
- public enum MicrosoftTechnology
- {
- CSharp,
- ASPNETMVC,
- SQLServer,
- WCF,
- SilverLight,
- }
- [Flags] public enum MicrosoftTechnology
- {
- CSharp = 1,
- ASPNETMVC = 2,
- SQLServer = 4,
- WCF = 8,
- SilverLight = 16,
- }
- /// <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();
- else18 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;
- }
- public enum CustomerType
- {
- Trader = 0,
- Supplier = 1,
- Logistics = 2,
- }
讲到这里我想您应该不难理解:为了对枚举运用位操作时指定枚举值的缘故了。非(~)操作符这里就留给读者自己实践了。
二、为枚举进行本地化