ENUM帮助类

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;

namespace CommonFunction
{
public class EnumClass
{
private static object refLock = new object();
private static EnumClass instance=null;

public static EnumClass Instance
{
get {
lock (refLock)
{
if (instance == null)
{
lock (refLock)
{
instance
= new EnumClass();
}
}
}
return instance;
}
}


/// <summary>
/// 获取指定枚举类型的键值对集合
/// </summary>
/// <param name="type">枚举类型</param>
/// <returns></returns>
public Hashtable GetKeysAndValues(Type type)
{
if (!CheckType(type))
{
return null;
}

Hashtable list
= new Hashtable();
foreach (string key in Enum.GetNames(type))
{
string val=Enum.Format( type, Enum.Parse(type, key), "d");
list.Add(key,val);
}

return list;
}


/// <summary>
/// 获取枚举类型元素集合
/// </summary>
/// <param name="type">枚举类型</param>
/// <returns></returns>
public Array GetKeys(Type type)
{
if (!CheckType(type))
{
return null;
}

//检索指定枚举中常数值的数组
return Enum.GetValues(type);
}


/// <summary>
/// 检验枚举类型
/// </summary>
/// <param name="type">类型</param>
/// <returns></returns>
private bool CheckType(Type type)
{
if (type == null)
{
return false;
}

if (!type.IsEnum)
{
throw new Exception(type.FullName + "不是枚举类型");
}

return true;
}


/// <summary>
/// 获取枚举类型值集合
/// </summary>
/// <param name="type">枚举类型</param>
/// <returns></returns>
public List<int> GetValues(Type type)
{
Array array
= GetKeys(type);
List
<int> list = new List<int>();
foreach (object obj in array)
{
list.Add((
int)obj);
}

return list;
}

}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace CommonFunction
{
class Program
{
enum Days { Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6 };
static void Main(string[] args)
{
Hashtable hashtable
= EnumClass.Instance.GetKeysAndValues(typeof(Days));
Console.WriteLine(
"---------枚举类型键值对---------");
foreach (DictionaryEntry de in hashtable)
{
Console.WriteLine(de.Key
+" = "+de.Value);
}
Console.WriteLine();

Console.WriteLine(
"---------枚举类元素---------");
Array array
= EnumClass.Instance.GetKeys(typeof(Days));
foreach (Days day in array)
{
Console.WriteLine(day);
}
Console.WriteLine();

Console.WriteLine(
"---------枚举类值---------");
List
<int> list = EnumClass.Instance.GetValues(typeof(Days));
foreach (int i in list)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
posted @ 2011-03-03 08:47  啊汉  阅读(664)  评论(1编辑  收藏  举报