Can I add extension methods to an existing static class?

前端 未结 15 1967
慢半拍i
慢半拍i 2020-11-22 07:23

I\'m a fan of extension methods in C#, but haven\'t had any success adding an extension method to a static class, such as Console.

For example, if I want to add an e

15条回答
  •  余生分开走
    2020-11-22 07:45

    You CAN do this if you are willing to "frig" it a little by making a variable of the static class and assigning it to null. However, this method would not be available to static calls on the class, so not sure how much use it would be:

    Console myConsole = null;
    myConsole.WriteBlueLine("my blue line");
    
    public static class Helpers {
        public static void WriteBlueLine(this Console c, string text)
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine(text);
            Console.ResetColor();
        }
    }
    

提交回复
热议问题