C#中获得某个枚举的所有名称

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System;
using System.Collections.Generic;

public static class EnumHelper
{
    public static List<string> AskEnumNames<T>() where T : Enum
    {
        Type enumType = typeof(T);
        List<string> enumNames = new List<string>();

        foreach (string name in Enum.GetNames(enumType))
        {
            enumNames.Add(name);
        }

        return enumNames;
    }
}

// 使用示例
public enum Colors
{
    Red,
    Green,
    Blue
}

class Program
{
    static void Main(string[] args)
    {
        List<string> enumNames = EnumHelper.AskEnumNames<Colors>();

        foreach (string name in enumNames)
        {
            Console.WriteLine(name);
        }
    }
}

输出结果如下:

用以上方法即可正常获取某个枚举的所有名称。

下面附件一个C#的反射的典型例子:

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Reflection;

namespace ReflectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 通过反射创建类型的实例
            Type myType = typeof(MyClass);
            object myInstance = Activator.CreateInstance(myType, new object[] { "Hello" });

            // 获取并调用类型的方法
            MethodInfo myMethod = myType.GetMethod("MyMethod");
            myMethod.Invoke(myInstance, new object[] { "World" });
        }
    }

    class MyClass
    {
        public MyClass(string message)
        {
            Console.WriteLine(message);
        }

        public void MyMethod(string message)
        {
            Console.WriteLine(message);
        }
    }
}

运行结果:

这个例子,利用反射机制构造了对象,并且调用了成员函数。

相关推荐
奋发向前wcx12 分钟前
CSP-J复赛模拟赛1 王晨旭补题 2026.10.2
java·开发语言
周杰伦fans18 分钟前
轻量模型高并发推理优化技巧
开发语言·人工智能·c#
Frank_refuel22 分钟前
【C++项目】手撕JRpc框架(单机怎么优化到分布式思想)
开发语言·c++
周杰伦fans32 分钟前
C#对话摘要降低Token消耗
人工智能·后端·c#
可乐鸡翅yeah_40 分钟前
fmp4 碎片 MP4 格式 HLS 流,和传统 TS 分片有什么不一样
开发语言·javascript·ios·音视频·safari·m3u8·m3u8在线播放
流形填表43 分钟前
多校区题库标准化:Excel模板与校验脚本
开发语言·python
步行cgn1 小时前
AOP 通知的类型详解
开发语言
weixin_307779131 小时前
从“人操作仪器”到“Agent 自主发现”:OPL 金属材料自驱动实验室 MVP 技术论述
开发语言·人工智能·算法·架构
笑鸿的学习笔记1 小时前
C++笔记之SIMD与SSE指令集
开发语言·c++·笔记
福兮说2 小时前
URL 编码的七个坑:c++ 传到后端变空格、%25 套娃、截断 emoji 直接报错
开发语言·前端·javascript·node.js·url