You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
3.3 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
/// <summary>
/// 枚举拓展
/// </summary>
namespace Common
{
/// <summary>
/// 枚举拓展
/// </summary>
public static class EnumExtensions
{
private static Dictionary<string, Dictionary<string, string>> enumCache;
private static Dictionary<string, Dictionary<string, string>> EnumCache
{
get
{
if (enumCache == null)
{
enumCache = new Dictionary<string, Dictionary<string, string>>();
}
return enumCache;
}
set { enumCache = value; }
}
/// <summary>
///根据枚举Name获取枚举value
/// </summary>
/// <param name="enumType"></param>
/// <param name="enumName"></param>
/// <returns></returns>
public static int GetEnumValue(Type enumType, string enumName)
{
try
{
if (!enumType.IsEnum)
throw new ArgumentException("enumType必须是枚举类型");
var values = Enum.GetValues(enumType);
var ht = new Hashtable();
foreach (var val in values)
{
ht.Add(Enum.GetName(enumType, val), val);
}
return (int)ht[enumName];
}
catch (Exception e)
{
throw e;
}
}
/// <summary>
/// 获得枚举提示文本
/// </summary>
/// <param name="en"></param>
/// <returns></returns>
public static string GetEnumText(this Enum en)
{
string enString = string.Empty;
if (null == en) return enString;
var type = en.GetType();
enString = en.ToString();
if (!EnumCache.ContainsKey(type.FullName))
{
var fields = type.GetFields();
Dictionary<string, string> temp = new Dictionary<string, string>();
foreach (var item in fields)
{
var attrs = item.GetCustomAttributes(typeof(EnumTextAttribute), false);
if (attrs.Length == 1)
{
var v = ((EnumTextAttribute)attrs[0]).Value;
temp.Add(item.Name, v);
}
}
try
{
EnumCache.Add(type.FullName, temp);
}
catch { }
}
if (EnumCache[type.FullName].ContainsKey(enString))
{
return EnumCache[type.FullName][enString];
}
return enString;
}
}
/// <summary>
/// 枚举描述
/// </summary>
public class EnumTextAttribute : Attribute
{
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public EnumTextAttribute(string value)
{
Value = value;
}
/// <summary>
///
/// </summary>
public string Value { get; set; }
}
}