C#中枚举的使用
2021-01-19 02:38
标签:== 类型 eva eval collect lin nat sorted for 枚举大家都不陌生,但是最近看到有的人,还在是页面上写死,如果枚举增减时,还要去页面去手动修改,今天我们来看看枚举的处理方式,这里说一下,我用的测试程序是.net core 3.1。 不多墨迹,直接上代码: 定义枚举: 枚举的辅助类,这里说明一下,我是通过获取枚举上的特性来处理的: EnumUtil.cs 定义一个调用类,当然你也可以直接调用: CommonEnumsDict.cs 最后调用: Program.cs 结果: key:-1,value:已删除 你最喜欢的代码:点击下载 C#中枚举的使用 标签:== 类型 eva eval collect lin nat sorted for 原文地址:https://www.cnblogs.com/itmu89/p/12164023.htmlusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace ConsoleApp1
{
public enum Status
{
[Description("已删除")]
Deleted = -1,
[Description("未处理")]
Init = 0,
[Description("正常")]
Normal = 1
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
namespace ConsoleApp1
{
public static class EnumUtil
{
///
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApp1
{
public class CommonEnumsDict
{
public static readonly Dictionaryint, string> StatusDict;
public static readonly Dictionarystring, string> StatusStrDict;
static CommonEnumsDict()
{
StatusDict = EnumUtil.GetEnumIntNameDict(Status.Normal);
StatusStrDict = EnumUtil.GetEnumVarNameDict(Status.Normal);
}
}
}
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
foreach (var item in CommonEnumsDict.StatusDict)
{
Console.WriteLine("key:" + item.Key + ",value:" + item.Value);
}
Console.WriteLine("--------------------------");
var PayValues = Enum.GetValues(typeof(Status));
foreach (var v in PayValues)
{
var name = EnumUtil.GetDesc((Status)v);
Console.WriteLine("key:" + (int)v + ",value:" + name);
}
Console.WriteLine("--------------------------");
foreach (var item in CommonEnumsDict.StatusStrDict)
{
Console.WriteLine("key:" + item.Key + ",value:" + item.Value);
}
var del = Status.Deleted.GetAttribute();
Console.WriteLine("del:" + del.Description);
Console.ReadLine();
}
}
}
key:0,value:未处理
key:1,value:正常
--------------------------
key:0,value:未处理
key:1,value:正常
key:-1,value:已删除
--------------------------
key:Deleted,value:已删除
key:Init,value:未处理
key:Normal,value:正常
del:已删除