无法获取枚举类型的扩展方法

我遇到的问题是创建扩展方法!


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

}

我希望上面代码中的注释真的能说明问题——我假设我在做一个巨大的假设并且把它弄错了。


然而,我宁愿通过允许任何枚举调用此功能来使其更有用。最终目标是这样的


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;

}


牛魔王的故事
浏览 102回答 2
2回答

天涯尽头无女友

扩展方法不直接作用于类型,而是作用于该类型的值。所以像TestEnum&nbsp;Val&nbsp;=&nbsp;TestEnum&nbsp;One; &nbsp;var&nbsp;b&nbsp;=&nbsp;Val.TestMethod();

鸿蒙传说

如果您需要 中所有枚举的列表List<string>,那么您可以尝试类似List<string>&nbsp;enumList&nbsp;=&nbsp;Enum.GetNames(typeof(TestEnum)).ToList();这将返回包含的字符串列表&nbsp;&nbsp;//"One",&nbsp;"Two",&nbsp;"Three",&nbsp;"Four"
打开App,查看更多内容
随时随地看视频慕课网APP