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

运行结果:

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

相关推荐
唐青枫1 小时前
C#.NET 数据库开发提速秘籍:SqlSugar 实战详解
c#·.net
mudtools17 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix1 天前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz1 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题1 天前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说1 天前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号1 天前
Qt 中 OPC UA 通讯实战
开发语言·qt