欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C# 声明枚举、枚举值描述 获取枚举值字符串 根据枚举获取枚举值描述

程序员文章站 2022-06-12 17:14:27
...

一、声明枚举值、枚举值描述

using System.ComponentModel;

public enum status
{
	/// <summary>
	/// 取消
	/// </summary>
	[Description("取消")]
	cancel,
	/// <summary>
	/// 提交
	/// </summary>
	[Description("提交")]
	submit,
	/// <summary>
	/// 同意
	/// </summary>
	[Description("批准")]
	pass,
	/// <summary>
	/// 驳回
	/// </summary>
	[Description("驳回")]
	reject
}

二、获取枚举值字符串、根据枚举获取枚举值描述

/// <summary>
/// 获取枚举描述信息
/// </summary>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetEnumDescription(this Enum enumValue) {
	string str = enumValue.ToString();
	System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
	object[] objs = field.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute) , false);
	if (objs == null || objs.Length == 0)
		return str;
	System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
	return da.Description;
}

/*
示例:string statusDes = status.submit.GetEnumDescription();
*/

/// <summary>
/// 枚举字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="enumValue"></param>
/// <returns></returns>
public static string GetEnumString<T>(this Enum enumValue) {
	return Enum.GetName(typeof(T) , enumValue);//推荐  
}

/*
示例:string status = status.submit.GetEnumString<status>();
*/

/// <summary>
/// 根据Description获取枚举
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="description">枚举描述</param>
/// <returns>枚举</returns>
public static string GetEnumName<T>(string description)
{
	Type _type = typeof(T);
	foreach (FieldInfo field in _type.GetFields())
	{
		DescriptionAttribute[] _curDesc = field.GetDescriptAttr();
		if (_curDesc != null && _curDesc.Length > 0)
		{
			if (_curDesc[0].Description == description)
				return field.GetValue(null).ToString();
		}
	}

	return null;
}

/*
示例:string status = GetEnumName<status>("提交");
*/