using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
namespace ConsoleApp4
{
static class Program
{
public static DB EnumObj { get; set; }
static void Main(string[] args)
{
var aaa = EnumObj.Split();
var bbb = (DB)7;
var ccc = (DB)15;
//遍历枚举
foreach (DB enum2 in Enum.GetValues(typeof(DB)))
{
//enum2 = DB.Read;
var Int = (int)enum2;
var Str = enum2.ToString();
var Description = GetDescriptionByEnum(enum2);
}
Console.ReadKey();
}
// Flags 可以让枚举值以枚举值之和形式提现。有一个前提:(int)大的枚举值必须大过其小于此值枚举值之和
//比如:ReadWrite > None + Write + Read
[Flags]
public enum DB
{
None = 0,
Write = 1,
[Description("写")]
Read = 2,
ReadWrite = 4,
Max = 8
}
//枚举、字符串、数字相互转换
public static int EnumConvertToInt(DB db) => (int)db;
public static string EnumConvertToString(DB db) => db.ToString();
public static DB StringConvertToEnum(string str) => (DB)Enum.Parse(typeof(DB), str);
public static DB IntConvertToEnum(int i) => (DB)i;
// 将枚举转化为IEnumerable列表
public static IEnumerable<T> Split<T>(this T enums) => Enum.GetValues(enums.GetType()).Cast<T>();
/// <summary>
/// 获取枚举的 Description 值
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetDescriptionByEnum(Enum enumValue)
{
string value = enumValue.ToString();
FieldInfo field = enumValue.GetType().GetField(value);
//获取描述属性
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
//当描述属性没有时,直接返回名称
return objs.Length == 0 ? value : ((DescriptionAttribute)objs[0]).Description;
}
}
}