您的位置:首页 > 编程语言 > C#

C#对枚举的常用操作

2012-05-06 15:08 435 查看
枚举操作类:

public partial class XEnumHelper
{
/// <summary>
/// 获得枚举的所有枚举项
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static IList<string> GetEnums(Type enumType)
{
IList<string> enums = new List<string>();

foreach (string s in Enum.GetNames(enumType))
{
enums.Add(s);
}

return enums;
}

/// <summary>
/// 将字符串转换为枚举
/// </summary>
/// <param name="enumType">枚举类型</param>
/// <param name="strValue">字符串值</param>
/// <returns></returns>
public static object String2Enum(Type enumType, string strValue)
{
return Enum.Parse(enumType, strValue);
}
}


枚举定义:

public enum OperateType
{
None = 0,
Add = 1,
Edit = 2,
Delete = 3
}


客户端调用:

static void Main(string[] args)
{
//获取枚举的常数值
OperateType opreateType = OperateType.Edit;
int num = (int)opreateType;
Console.WriteLine("枚举项Edit的常数值为:{0}", num);

//字符串转换为枚举值
string optType = "Delete";
opreateType = (OperateType)XEnumHelper.String2Enum(typeof(OperateType), optType);
Console.WriteLine("字符串值:{0}转换为枚举类型:{1}", optType, opreateType);

//通过枚举的常数值获得枚举值
num = 3;
opreateType = (OperateType)num;
Console.WriteLine("枚举项常数值为3对应的枚举项为:{0}", opreateType);

//列举枚举值
IList<string> enums = XEnumHelper.GetEnums(typeof(OperateType));
int loopNo = 0;
foreach (string e in enums)
{
loopNo += 1;
Console.WriteLine("枚举项{0}:{1}", loopNo, e);
}

Console.Read();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: