我是c#中扩展方法的粉丝,但还没有成功地将扩展方法添加到静态类中,比如Console。

例如,如果我想添加一个名为“WriteBlueLine”的扩展到控制台,这样我就可以:

Console.WriteBlueLine("This text is blue");

我尝试通过添加一个本地的公共静态方法,并将Console作为“this”参数…但是不行!

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

这没有添加'WriteBlueLine'方法控制台…我做错了吗?或者要求不可能的事情?


当前回答

不。扩展方法定义需要所扩展类型的实例。这是不幸的;我不知道为什么需要……

其他回答

这是不可能的。

是的,我认为MS犯了一个错误。

他们的决定没有意义,迫使程序员编写(如上所述)一个毫无意义的包装器类。

下面是一个很好的例子:试图扩展静态MS单元测试类Assert:我想要一个Assert方法AreEqual(x1,x2)。

做到这一点的唯一方法是指向不同的类或围绕100个不同的Assert方法编写包装器。为什么! ?

如果决定允许实例的扩展,我认为没有任何逻辑理由不允许静态扩展。一旦实例可以扩展,关于分段库的争论就站不住脚了。

也许你可以用你的自定义命名空间和相同的类名添加一个静态类:

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);
        }
    }
}

不能向类型添加静态方法。只能向某个类型的实例添加(伪)实例方法。

this修饰符的作用是告诉c#编译器将实例传递到。作为静态/扩展方法的第一个参数。

在向类型添加静态方法的情况下,没有为第一个参数传递实例。

我试着用系统来做这件事。当时我正在学习扩展方法,但没有成功。正如其他人提到的,原因是扩展方法需要类的实例。

虽然Console的方法是静态的,但它的静态方法Write()和WriteLine()只是分别将调用重定向到Console. out .Write()和Console. out .WriteLine()。Out是一个实例,其类型派生自抽象类TextWriter。这使得为TextWriter定义扩展方法成为可能:

public static class ConsoleTextWriterExtensions
{
    public static void WriteBlueLine(this TextWriter writer, string text)
    {
        Console.ForegroundColor = ConsoleColor.Blue;
        writer.WriteLine(text);
        Console.ResetColor();
    }

    public static void WriteUppercase(this TextWriter writer, string text)
    {
        writer.Write(text.ToUpper());
    }
}

然后可以像这样调用该方法:

Console.Out.WriteBlueLine();

最好的部分是标准错误流实例Console的类型。错误也源于TextWriter,这使得相同的扩展方法也可用于控制台。错误:

Console.Error.WriteBlueLine();

如果您已经定义了像WriteTable()这样的扩展方法(用于将表写入控制台),那么这可能非常有用,因为您还可以将它用于错误流或TextWriter的任何其他对象。

新版本的c#甚至可以用using static语句来获得控制台的红色。前缀:

using static System.Console;

Out.WriteBlueLine("A blue line");
Error.WriteBlueLine("A blue line");