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

运行结果:

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

相关推荐
HAPPY酷1 分钟前
C++ 内存泄漏排查:从裸 new 到 RAII 修复,附 ASan 实战
开发语言·c++
十年Java程序媛24 分钟前
Java 面试常问 this、super:构造方法调用顺序避坑
java·开发语言·spring boot·面试·个人开发
人丰29 分钟前
一次生产卡顿复盘:BI 数据抽取引发 PostgreSQL 长事务事故
数据库·c#
yuniko-n43 分钟前
【JUC】内存屏障
java·开发语言
Linux运维技术栈1 小时前
近期 PHP 高危安全风险排查与多环境升级实操
开发语言·安全·php
Fnetlink11 小时前
Fnet 云网安 261023
运维·开发语言·网络·人工智能·安全·web安全·php
ESDWAN1 小时前
SD-WAN 主备切换为什么仍会断网?从检测、切换到会话恢复分析
运维·开发语言·网络·php
jimy11 小时前
lvalue、xvalue、prvalue(二):引用是哪一类?
开发语言·c++·1024程序员节
cxyxixiy1 小时前
数智码力:数据核对不用人工比对,Python 快速完成多表格差异校验
开发语言·python·学习
一个风轻云淡1 小时前
从 int $0x80 到 iret:用 gdb 把 getpid 走一遍
linux·c语言·开发语言·汇编