using System;
using System.Linq;
namespace NCTools.Helper
{
public static class EnumHelper<T> where T : struct
{
#region 内部处理
static void VerifyIndex(int index)
{
if (!Contains(index))
{
throw new Exception($"枚举[{typeof(T).Name}]不包含索引[{index}]");
}
}
#endregion
public static int Count()
{
return GetNames().Length;
}
public static TValue[] GetValues<TValue>()
{
return (TValue[])Enum.GetValues(typeof(T));
}
public static string[] GetNames()
{
return Enum.GetNames(typeof(T));
}
public static string GetName(int index)
{
VerifyIndex(index);
return Enum.GetName(typeof(T), index);
}
public static string GetName(T obj)
{
return Enum.GetName(typeof(T), obj);
}
public static int GetIndex(T obj)
{
var name = GetName(obj);
return GetIndex(name);
}
public static int GetIndex(string name)
{
return Parse<int>(name);
}
public static T GetObject(string name)
{
return Parse<T>(name);
}
public static T GetObject(int index)
{
VerifyIndex(index);
return (T)Enum.ToObject(typeof(T), index);
}
public static TValue Parse<TValue>(string name)
{
return (TValue)Enum.Parse(typeof(T), name, true);
}
public static bool TryParse(string name, out T obj)
{
return Enum.TryParse(name, out obj);
}
public static bool Contains<TValue>(TValue value)
{
return GetValues<TValue>().Contains(value);
}
public static bool Contains(string name)
{
return GetNames().Contains(name);
}
}
}