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

C# 枚举(Enum ) 应用总结

2012-09-05 16:21 477 查看
  1. 枚举定义

  普通情况下,枚举字段常数可以是汉字,英文,但不能是数字。当不指定值时,默认值从0开始,如下:待处理=0,审核中=1

public enum Status
{
待处理,
审核中,
交易终止,
交易完成
}


  当需要自定义值时则直接在后面赋值即可

public enum Status
{
待处理 = 0,
审核中 = 10,
交易终止 = 20,
交易完成 = 99
}


  定义枚举Description

public enum Status
{
[Description("未审核")]
Untreated = 0,
[Description("审核中")]
Process = 10,
[Description("交易终止")]
Cancel = 20,
[Description("交易完成")]
Over= 99
}


  2.枚举取值

  通过枚举类型,常量名称取key

Status.待处理


  通过枚举类型,和key,获指定的常量名称

Type type = typeof(Status);
String enumName =  Enum.GetName(type, key);


  通过枚举类型,和key,获指枚举Description

public static string GetEnumDescription(Type enumType, int key)
{
FieldInfo EnumInfo = enumType.GetField(Enum.GetName(enumType, key));
DescriptionAttribute[] attributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return GetEnumText(enumType, key.ToString());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: