我是C#中扩展方法的粉丝,但是没有成功将扩展方法添加到静态类,例如Console.
例如,如果我想向Console添加一个名为'WriteBlueLine'的扩展,那么我可以去:
Console.WriteBlueLine("This text is blue");
Run Code Online (Sandbox Code Playgroud)
我尝试通过添加一个本地的公共静态方法,将Console作为'this'参数...但没有骰子!
public static class Helpers {
public static void WriteBlueLine(this Console c, string text)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(text);
Console.ResetColor();
}
}
Run Code Online (Sandbox Code Playgroud)
这没有向Console添加'WriteBlueLine'方法......我做错了吗?或者要求不可能?
不知道我在这里做错了什么.无法识别扩展方法.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using StringExtensions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
RunTests();
}
static void RunTests()
{
try
{
///SafeFormat
SafeFormat("Hi There");
SafeFormat("test {0}", "value");
SafeFormat("test missing second value {0} - {1}", "test1");
SafeFormat("{0}");
//regular format
RegularFormat("Hi There");
RegularFormat("test {0}", "value");
RegularFormat("test missing second value {0} - {1}", "test1");
RegularFormat("{0}");
///Fails to recognize the extension method here
string.SafeFormat("Hello");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
} …Run Code Online (Sandbox Code Playgroud) 我不喜欢字符串的行为方式,还有一些我想改变的其他事情.
看起来字符串无法扩展,因为它是一个密封的类.
还有另外一种方法吗?我可以复制源代码并创建我自己的类但是它与字符串不兼容,或者我可以使它兼容吗?