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.
53 lines
1.7 KiB
C#
53 lines
1.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Linq;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace HighWayIot.Common
|
|
{
|
|
/// <summary>
|
|
/// 通用工具类
|
|
/// </summary>
|
|
public class GeneralUtils
|
|
{
|
|
/// <summary>
|
|
/// 获取枚举类值的description元数据(没有Des返回名字)
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public static string GetEnumStringDescription(Enum enumValue)
|
|
{
|
|
string value = enumValue.ToString();
|
|
FieldInfo field = enumValue.GetType().GetField(value);
|
|
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
|
|
if (objs.Length == 0) //当描述属性没有时,直接返回名称
|
|
return value;
|
|
DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
|
|
return descriptionAttribute.Description;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取枚举类的键值对
|
|
/// </summary>
|
|
/// <typeparam name="T"></typeparam>
|
|
/// <returns></returns>
|
|
public static IEnumerable<KeyValuePair<string, int>> GetEnumKeyValuePairs<T>() where T : Enum
|
|
{
|
|
var enumType = typeof(T);
|
|
var fields = enumType.GetFields();
|
|
|
|
foreach (var fi in fields)
|
|
{
|
|
if (fi.FieldType != enumType || !fi.IsLiteral)
|
|
continue;
|
|
|
|
var name = fi.Name;
|
|
var value = (int)enumType.GetField(name).GetValue(null);
|
|
yield return new KeyValuePair<string, int>(name, value);
|
|
}
|
|
}
|
|
}
|
|
}
|