2025-03-28 09:49:56 +08:00

96 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace Transmission.SDK
{
public class EnumHelper
{
/// <summary>
/// 获取变量名称
/// </summary>
/// <param name="exp">变量</param>
/// <returns></returns>
public static string GetVarName(Expression<Func<string, string>> exp)
{
return ((MemberExpression)exp.Body).Member.Name;
}
/// <summary>
/// 获取枚举项描述信息 例如GetEnumDesc(Days.Sunday)
/// </summary>
/// <param name="en">枚举项 如Days.Sunday</param>
/// <returns></returns>
public static string GetEnumDesc(System.Enum en)
{
Type type = en.GetType();
MemberInfo[] memInfo = type.GetMember(en.ToString());
if (memInfo != null && memInfo.Length > 0)
{
object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attrs != null && attrs.Length > 0)
return ((DescriptionAttribute)attrs[0]).Description;
}
return en.ToString();
}
///<summary>
/// EnumToNameValueCollection
///</summary>
///<param name="enumType">Type,该参数的格式为typeof(需要读的枚举类型)</param>
///<returns>键值对</returns>
public static NameValueCollection EnumToNVC(Type enumType)
{
NameValueCollection nvc = new NameValueCollection();
Type typeDescription = typeof(DescriptionAttribute);
FieldInfo[] fields = enumType.GetFields();
string strText = string.Empty;
string strValue = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute aa = (DescriptionAttribute)arr[0];
strText = aa.Description;
}
else
{
strText = field.Name;
}
nvc.Add(strValue, strText);
}
}
return nvc;
}
///<summary>
/// EnumToDictionary
///</summary>
///<param name="enumType"></param>
///<returns>Dictionary枚举项描述</returns>
public static Dictionary<string, string> EnumToDictionary(Type enumType)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
FieldInfo[] fieldinfos = enumType.GetFields();
foreach (FieldInfo field in fieldinfos)
{
if (field.FieldType.IsEnum)
{
Object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
dic.Add(field.Name, ((DescriptionAttribute)objs[0]).Description);
}
}
return dic;
}
}
}