Can I add extension methods to an existing static class?(我可以将扩展方法添加到现有的静态类吗?)
问题描述
我是 C# 中的扩展方法的粉丝,但没有成功将扩展方法添加到静态类,例如 Console
.
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
.
例如,如果我想在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");
我尝试通过添加一个本地的公共静态方法,将 Console
作为 'this
' 参数...但没有骰子!
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();
}
}
这没有向 Console
添加一个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 variable (value) for 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" );
}
}
这篇关于我可以将扩展方法添加到现有的静态类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以将扩展方法添加到现有的静态类吗?


基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01