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

运行结果:

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

相关推荐
CodeWithMe3 分钟前
【C/C++】EBO空基类优化介绍
开发语言·c++
404.Not Found13 分钟前
Day46 Python打卡训练营
开发语言·python
love530love14 分钟前
【PyCharm必会基础】正确移除解释器及虚拟环境(以 Poetry 为例 )
开发语言·ide·windows·笔记·python·pycharm
凌辰揽月16 分钟前
Web后端基础(基础知识)
java·开发语言·前端·数据库·学习·算法
海奥华220 分钟前
go中的接口返回设计思想
开发语言·后端·golang
lifallen22 分钟前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法
运维开发王义杰22 分钟前
Python: 告别 ModuleNotFoundError, 解决 pipx 环境下 sshuttle 缺少 pydivert 依赖的终极指南
开发语言·python
k要开心23 分钟前
从C到C++语法过度1
开发语言·c++
小吕学编程26 分钟前
策略模式实战:Spring中动态选择商品处理策略的实现
java·开发语言·设计模式
q567315231 小时前
IBM官网新闻爬虫代码示例
开发语言·分布式·爬虫