EnumHelper.cs

本文介绍了一个用于操作枚举类型的工具类,该类提供了一系列静态方法来帮助开发者更方便地获取枚举值、名称、索引等信息,并验证枚举的有效性。
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);
        }

    }
}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值