Enumeration extension methods

前端 未结 7 1210
长发绾君心
长发绾君心 2020-12-01 07:09

In vs2008, is it possible to write an extension methods which would apply to any enumeration.

I know you can write extension methods against a specific enumeration,

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 07:49

    Here's another example - also nicer IMHO than having to create and initialize a temp variable.

    public static class ExtensionMethods 
    {
        public static void ForEach(this Enum enumType, Action action)
        {
            foreach (var type in Enum.GetValues(enumType.GetType()))
            {
                action((Enum)type);
            }
        }
    }
    
    public enum TestEnum { A,B,C } 
    public void TestMethod() 
    {
        default(TestEnum).ForEach(Console.WriteLine); 
    } 
    

提交回复
热议问题