C#枚举案例
一、普通调用
public enum NoticeType
{
Notice = 'A',
LabRule = 'H',
HotInformation = 'N',
Column = 'C',
All = '1',
Null = '0'
}
private void button1_Click(object sender, EventArgs e)
{
//新建枚举类型
NoticeType noticeType1 = NoticeType.Column;
//把枚举类型转换为string d="Column"
string d = noticeType1.ToString();
//取得枚举类型的基数 'C'
char dd = (char)noticeType1;
//通过基数取得对应的枚举类型
NoticeType noticeType2 = (NoticeType)Char.Parse("A");//Notice
//通过名称取得枚举类型
NoticeType noticeType3 = (NoticeType)Enum.Parse(typeof(NoticeType), "Notice");
}
二、获取描述信息
[Description("会员等级")]
enum MemberLevel
{
[Description("金牌会员")]
gold = 1,
[Description("银牌会员")]
silver = 2,
[Description("铜牌会员")]
copper = 3
}
/// <summary>
///
/// </summary>
/// <param name="value">枚举值</param>
/// <param name="isTop">是否是顶级标题的描述信息</param>
/// <returns></returns>
public static string GetDescription(this Enum value, bool isTop = false)
{
Type enumType = value.GetType();
DescriptionAttribute attr = null;
if (isTop)
{
attr = (DescriptionAttribute)Attribute.GetCustomAttribute(enumType, typeof(DescriptionAttribute));
}
else
{
// 获取枚举常数名称。
string name = Enum.GetName(enumType, value);
if (name != null)
{
// 获取枚举字段。
FieldInfo fieldInfo = enumType.GetField(name);
if (fieldInfo != null)
{
// 获取描述的属性。
attr = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute), false) as DescriptionAttribute;
}
}
}
if (attr != null && !string.IsNullOrEmpty(attr.Description))
return attr.Description;
else
return string.Empty;
}
调用
MemberLevel gold = MemberLevel.gold;
Console.WriteLine(gold.GetDescription());
System.Console.Read();
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/15763922.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2020-01-04 C#实现DataTable转为Excel文件
2020-01-04 C#实现的对文件的重命名
2020-01-04 C#调用7z实现文件的压缩与解压
2020-01-04 C#实现文件Move操作和文件的Copy操作