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 分钟前
计算一个字符串在另一个字符串中出现次数
java·开发语言
froginwe115 分钟前
Bootstrap5 表格
开发语言
前端不太难11 分钟前
Navigation State 驱动的页面调试方法论
开发语言·前端·react.js
饕餮怪程序猿13 分钟前
订单分批算法设计与实现:基于商品相似性的智能分拣优化(C++)
开发语言·c++·算法
崇山峻岭之间35 分钟前
Matlab学习记录05
开发语言·学习·matlab
狗狗摇屁屁38 分钟前
JS手写防抖
开发语言·javascript·ecmascript
派大鑫wink41 分钟前
【Day7】构造方法与 this 关键字:初始化对象的正确姿势
java·开发语言
智算菩萨41 分钟前
实战:用 Python + 传统NLP 自动总结长文章
开发语言·人工智能·python
沐知全栈开发41 分钟前
WebForms HashTable 深入解析
开发语言
子夜江寒41 分钟前
基于 Python 库使用贝叶斯算法与逻辑森林
开发语言·python·算法