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

运行结果:

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

相关推荐
csdn_aspnet2 分钟前
WPF 做一个简单的电子签名板(一)
c#·wpf
玖笙&3 分钟前
✨WPF编程进阶【7.2】:动画类型(附源码)
c++·c#·wpf·visual studio
大炮走火20 分钟前
iOS在制作framework时,oc与swift混编的流程及坑点!
开发语言·ios·swift
她说彩礼65万23 分钟前
C# 容器实例生命周期
开发语言·c#
San30.32 分钟前
JavaScript 深度解析:从 map 陷阱到字符串奥秘
开发语言·javascript·ecmascript
十一.36644 分钟前
66-69 原型对象,toString(),垃圾回收
开发语言·javascript·原型模式
小小鱼儿飞3 小时前
QT音乐播放器18----新歌速递播放、隐藏顶部和底部工具栏、自定义ToolTips
开发语言·qt
穆雄雄3 小时前
Rust 程序适配 OpenHarmony 实践:以 sd 工具为例
开发语言·rust·harmonyos
0***143 小时前
Swift资源
开发语言·ios·swift
z***I3943 小时前
Swift Tips
开发语言·ios·swift