我可以扩展方法添加到现有的静态类? [英] Can I add extension methods to an existing static class?
问题描述
我在C#扩展方法球迷,但没有成功添加一个扩展方法静态类,如控制台。
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.
例如,如果我想添加一个扩展到控制台,所谓'WriteBlueLine',这样我就可以去:
For example, if I want to add an extension to Console, called 'WriteBlueLine', so that I can go:
Console.WriteBlueLine("This text is blue");
我想这通过添加一个地方,公共静态方法,用控制台作为一个'这个'参数...但没有骰子!
I tried this by adding a local, public static method, with Console as a 'this' parameter... but no dice!
public static class Helpers {
public static void WriteBlueLine(this Console c, string text)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(text);
Console.ResetColor();
}
}
这并没有一个'WriteBlueLine方法添加到控制台...我做错了?或缘木求鱼?
This didn't add a 'WriteBlueLine' method to Console... am I doing it wrong? Or asking for the impossible?
推荐答案
没有。扩展方法需要一个对象的一个实例。不过,您可以写周围的 ConfigurationManager中
接口的静态包装。如果实施包装,不需要扩展方法,因为你可以直接添加方法。
No. Extension methods require an instance of an object. You can however, write a static wrapper around the ConfigurationManager
interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
public static class ConfigurationManagerWrapper
{
public static ConfigurationSection GetSection( string name )
{
return ConfigurationManager.GetSection( name );
}
.....
public static ConfigurationSection GetWidgetSection()
{
return GetSection( "widgets" );
}
}
这篇关于我可以扩展方法添加到现有的静态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!