Can I add extension methods to an existing static class?

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

    Maybe you could add a static class with your custom namespace and the same class name:

    using CLRConsole = System.Console;
    
    namespace ExtensionMethodsDemo
    {
        public static class Console
        {
            public static void WriteLine(string value)
            {
                CLRConsole.WriteLine(value);
            }
    
            public static void WriteBlueLine(string value)
            {
                System.ConsoleColor currentColor = CLRConsole.ForegroundColor;
    
                CLRConsole.ForegroundColor = System.ConsoleColor.Blue;
                CLRConsole.WriteLine(value);
    
                CLRConsole.ForegroundColor = currentColor;
            }
    
            public static System.ConsoleKeyInfo ReadKey(bool intercept)
            {
                return CLRConsole.ReadKey(intercept);
            }
        }
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    Console.WriteBlueLine("This text is blue");   
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine(ex.StackTrace);
                }
    
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey(true);
            }
        }
    }
    

提交回复
热议问题