Can I add extension methods to an existing static class?

前端 未结 15 1748
慢半拍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:40

    You can use a cast on null to make it work.

    public static class YoutTypeExtensionExample
    {
        public static void Example()
        {
            ((YourType)null).ExtensionMethod();
        }
    }
    

    The extension:

    public static class YourTypeExtension
    {
        public static void ExtensionMethod(this YourType x) { }
    }
    

    YourType:

    public class YourType { }
    

提交回复
热议问题