我遇到的問題是創(chuàng)建擴(kuò)展方法!public enum TestEnum{ One, Two, Three, Four}public static class EnumExtension{ public static bool TestMethod(this TestEnum e) { return false; }}[TestMethod]public void TestAll(){ var result = TestEnum. ; //this only gives the values of the enum (One, Two, Three, Four), there is no option to call the extension method}我希望上面代碼中的注釋真的能說明問題——我假設(shè)我在做一個(gè)巨大的假設(shè)并且把它弄錯(cuò)了。然而,我寧愿通過允許任何枚舉調(diào)用此功能來使其更有用。最終目標(biāo)是這樣的public static IEnumerable<string> ConvertToList(this Enum e){ var result = new List<string>(); foreach (string name in Enum.GetNames(typeof(e))) //doesn't like e { result.Add(name.ToString()); } return result;}
2 回答

天涯盡頭無女友
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
擴(kuò)展方法不直接作用于類型,而是作用于該類型的值。
所以像
TestEnum Val = TestEnum One; var b = Val.TestMethod();

鴻蒙傳說
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果您需要 中所有枚舉的列表List<string>
,那么您可以嘗試類似
List<string> enumList = Enum.GetNames(typeof(TestEnum)).ToList();
這將返回包含的字符串列表
//"One", "Two", "Three", "Four"
- 2 回答
- 0 關(guān)注
- 120 瀏覽
添加回答
舉報(bào)
0/150
提交
取消