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

C# 枚举类型 enum

2018-01-09 10:47 621 查看
我个人感觉平日用到的enum应该是非常简单的,无非就是枚举和整数、字符串之间的转换。最近工作发现一些同事居然不太会用这个东东,于是就整理一下。

枚举类型是定义了一组“符号名称/值”配对。枚举类型是强类型的。每个枚举类型都是从system.Enum派生,又从system.ValueType派生,而system.ValueType又从system.Object派生,所以枚举类型是值类型。编译枚举类型时,C#编译器会把每个符号转换成类型的一个常量字段。C#编译器将枚举类型视为基元类型。因为enum是值类型,而所有的值类型都是sealed,所以在扩展方法时都不能进行约束。但是,若要限制参数为值类型,可用struct
约束。因为enum一般用于一个字符串和整数值,如果我们需要关联多个字符串的时候可以使用Description特性,如果枚举彼此需要与或运算,需要借助Flags特性,enum里面定义的字符常量其整数值默认从0开始。

看一下枚举定义:

public enum AwardType
{
/// <summary>
///1 积分
/// </summary>
[Description("积分")]
Integral = 1,

/// <summary>
/// 2 充值卡
/// </summary>
[Description("充值卡")]
RechargeCard = 2,

/// <summary>
/// 3 实物奖品
/// </summary>
[Description("实物奖品")]
Gift = 3,
}
public static class Extend
{
public static string Description<T>(this T instance) where T : struct
{
string str = string.Empty;
Type type = typeof(T);
if (!typeof(T).IsEnum)
{
throw new ArgumentException("参数必须是枚举类型");
}
var fieldInfo = type.GetField(instance.ToString());
if (fieldInfo != null)
{
var attr = fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
if (attr != null)
{
str = attr.Description;
}
else
{
str = fieldInfo.Name;
}

}
return str;
}

public static T GetEnum<T>(this string description)
{
var fieldInfos = typeof(T).GetFields();
foreach (FieldInfo field in fieldInfos)
{
DescriptionAttribute attr = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
if (attr != null && attr.Description == description)
{
return (T)field.GetValue(null);
}
else if (field.Name == description)
{
return (T)field.GetValue(null);
}
}
throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description");
}
}


编译后如下:



在编码的时候 必要的注释 不能缺少,如下

/// <summary>

/// 3 实物奖品

/// </summary>

这样VS在只能感知的时候就可以看到了。

而枚举的应用也非常简单:

static void Main(string[] args)
{
//枚举与整数转换
int giftInt = (int)AwardType.Gift;
var a = (AwardType)giftInt;
//枚举与字符串转换
string giftStr = AwardType.Gift.ToString();
Enum.TryParse(giftStr, out AwardType b);
///检测枚举是否有效
bool isdefine = Enum.IsDefined(typeof(AwardType), 1);
////获取枚举描述
string str = AwardType.Gift.Description();
////通过描述获取枚举
AwardType award = str.GetEnum<AwardType>();
Console.ReadKey();
}


这里枚举和其描述信息是直接通过反射来实现的,为了性能提高可以采用字典缓存数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: