C#實現(xiàn)獲得某個枚舉的所有名稱
更新時間:2025年01月21日 16:04:12 作者:秋月的私語
這篇文章主要為大家詳細介紹了C#如何實現(xiàn)獲得某個枚舉的所有名稱,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以參考一下
C#中獲得某個枚舉的所有名稱
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#的反射的典型例子:
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)建類型的實例 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); } } }
運行結果:
這個例子,利用反射機制構造了對象,并且調用了成員函數(shù)。
到此這篇關于C#實現(xiàn)獲得某個枚舉的所有名稱的文章就介紹到這了,更多相關C#獲得枚舉所有名稱內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!