C#實(shí)現(xiàn)獲得某個(gè)枚舉的所有名稱
C#中獲得某個(gè)枚舉的所有名稱
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);
}
}
}輸出結(jié)果如下:

用以上方法即可正常獲取某個(gè)枚舉的所有名稱。
下面附件一個(gè)C#的反射的典型例子:
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)
{
// 通過反射創(chuàng)建類型的實(shí)例
Type myType = typeof(MyClass);
object myInstance = Activator.CreateInstance(myType, new object[] { "Hello" });
// 獲取并調(diào)用類型的方法
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);
}
}
}運(yùn)行結(jié)果:

這個(gè)例子,利用反射機(jī)制構(gòu)造了對(duì)象,并且調(diào)用了成員函數(shù)。
到此這篇關(guān)于C#實(shí)現(xiàn)獲得某個(gè)枚舉的所有名稱的文章就介紹到這了,更多相關(guān)C#獲得枚舉所有名稱內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)綁定DataGridView與TextBox之間關(guān)聯(lián)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)綁定DataGridView與TextBox之間關(guān)聯(lián)的方法,涉及C#綁定控件關(guān)聯(lián)性的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-08-08
C#基于Whisper.net實(shí)現(xiàn)語(yǔ)音識(shí)別功能的示例詳解
在當(dāng)今數(shù)字化時(shí)代,語(yǔ)音識(shí)別技術(shù)已廣泛應(yīng)用于智能助手,語(yǔ)音轉(zhuǎn)文字,會(huì)議記錄等眾多領(lǐng)域,本文我們就來介紹一個(gè)強(qiáng)大的工具Whisper.net,看看如何在 C# 項(xiàng)目中利用它完成語(yǔ)音識(shí)別任務(wù)吧2025-06-06
C#(WinForm) ComboBox和ListBox添加項(xiàng)及設(shè)置默認(rèn)選擇項(xiàng)
這篇文章主要介紹了C#(WinForm) ComboBox和ListBox添加項(xiàng)及設(shè)置默認(rèn)選擇項(xiàng)的的相關(guān)資料,需要的朋友可以參考下2014-07-07
c# 冒泡排序算法(Bubble Sort) 附實(shí)例代碼
這篇文章主要介紹了c# 冒泡排序算法,需要的朋友可以參考下2013-10-10

