Can I add extension methods to an existing static class?

前端 未结 15 2002
慢半拍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:25

    I stumbled up on this thread while trying to find an answer to the same question the OP had. I didn't find the answer I wanted but I ended up doing this.

    public static class MyConsole
    {
        public static void WriteLine(this ConsoleColor Color, string Text)
        {
            Console.ForegroundColor = Color;
            Console.WriteLine(Text);   
        }
    }
    

    And I use it like this:

    ConsoleColor.Cyan.WriteLine("voilà");
    

提交回复
热议问题