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);
        }
    }
}

运行结果:

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

相关推荐
一念&3 小时前
每日一个C语言知识:C 数据类型
c语言·开发语言
椒颜皮皮虾྅3 小时前
【DeploySharp 】基于DeploySharp 的深度学习模型部署测试平台:安装和使用流程
人工智能·深度学习·开源·c#·openvino
迈火3 小时前
PuLID_ComfyUI:ComfyUI中的图像生成强化插件
开发语言·人工智能·python·深度学习·计算机视觉·stable diffusion·语音识别
wzg20163 小时前
vscode 配置使用pyqt5
开发语言·数据库·qt
板鸭〈小号〉5 小时前
Socket网络编程(1)——Echo Server
开发语言·网络·php
明天会有多晴朗5 小时前
C语言入门教程(第1讲):最通俗的C语言常见概念详解与实战讲解
c语言·开发语言·c++
爱上妖精的尾巴5 小时前
5-20 WPS JS宏 every与some数组的[与或]迭代(数组的逻辑判断)
开发语言·前端·javascript·wps·js宏·jsa
gopher95115 小时前
Go 语言的 panic 和 recover
开发语言·golang
豆沙沙包?5 小时前
2025年--Lc165--H637.二叉树的层平均值(二叉树的层序遍历)--Java版
java·开发语言
小蒜学长6 小时前
springboot二手儿童绘本交易系统设计与实现(代码+数据库+LW)
java·开发语言·spring boot·后端