我是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'方法......我做错了吗?或者要求不可能?
我有这个代码:
public static List<Phrase> selectedPhrases;
Run Code Online (Sandbox Code Playgroud)
和
if (!App.selectedPhrases.Any(x => x.Viewed == false))
return;
Run Code Online (Sandbox Code Playgroud)
有什么方法可以改变我声明 selectedPhrases 的方式,以便我可以以这种方式进行最后一次检查:
if (App.selectedPhrases.AllViewed())
return;
Run Code Online (Sandbox Code Playgroud)
我听说过扩展方法,但是可以像在我的代码中那样为 List 创建一个方法吗?