• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

C#中获取一个枚举的所有名称和值

使用下面的C#代码,可以遍历一个枚举中的所有名称(Names)和值(Values):

using System.Diagnostics;

namespace Net8EnumDemo
{
    enum TestEnume : int
    {
        Enum1 = 0,
        Enum2 = 1,
        Enum3 = 2
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            TestEnume[]? testEnume = Enum.GetValues(typeof(TestEnume)) as TestEnume[];

            Console.WriteLine("Names of TestEnume:");
            foreach (TestEnume e in testEnume!)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("Values of TestEnume:");
            foreach (TestEnume e in testEnume!)
            {
                Console.WriteLine(e.ToString("D"));
            }

            Console.WriteLine("Press any key to end...");
            Console.ReadLine();
        }
    }
}

上面的代码输出:

Names of TestEnume:
Enum1
Enum2
Enum3
Values of TestEnume:
0
1
2
Press any key to end...

所以可以看到,使用Enum.GetValues方法可以获取到C#中一个枚举的所有元素。

 

posted @ 2024-12-11 10:51  PowerCoder  阅读(236)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3