Can I add extension methods to an existing static class?

前端 未结 15 1969
慢半拍i
慢半拍i 2020-11-22 07:23

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.

For example, if I want to add an e

15条回答
  •  野性不改
    2020-11-22 07:31

    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" );
          }
     }
    

提交回复
热议问题