Cod*_*nis 26 c# console extension-methods
在查看这个问题及其答案时,我认为为System.Console
包含所需功能的扩展方法编写扩展方法是个好主意.
但是,当我尝试它时,我得到了这个编译错误
System.Console':静态类型不能用作参数
这是代码:
using System;
using System.Runtime.CompilerServices;
namespace ConsoleApplication1
{
public static class ConsoleExtensions
{
[Extension]
public static string TestMethod(this Console console, string testValue)
{
return testValue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否有另一种为静态类型创建扩展方法的方法?或者这是不可能的?
Seb*_*n K 23
正如Matt的回答中提到的那样,这是不可能的.
作为一种解决方法,您可以创建一个静态类,它将包装Console添加所需的功能.
public static class ConsoleEx
{
public static void WriteLineRed(String message)
{
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ForegroundColor = oldColor;
}
}
Run Code Online (Sandbox Code Playgroud)
这不是理想的,因为你必须添加那个小的"Ex",但如果那是任何(ehm)的安慰,那么代码就会很好地流动:
ConsoleEx.WriteLineRed("[ERROR]")
Run Code Online (Sandbox Code Playgroud)
Mat*_*kon 22
不幸的是,不可能.请参阅静态扩展方法
一些人建议:http: //madprops.org/blog/static-extension-methods/
...但它从来没有在.NET 4中完成.显然扩展属性在某种程度上可以实现,但后来被放弃了.
https://blogs.msdn.com/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx