How do I extend a class with c# extension methods?

后端 未结 9 1391
情书的邮戳
情书的邮戳 2020-12-04 10:48

Can extension methods be applied to the class?

For example, extend DateTime to include a Tomorrow() method that could be invoked like:

DateTime.Tomor         


        
9条回答
  •  甜味超标
    2020-12-04 11:15

    I was looking for something similar - a list of constraints on classes that provide Extension Methods. Seems tough to find a concise list so here goes:

    1. You can't have any private or protected anything - fields, methods, etc.

    2. It must be a static class, as in public static class....

    3. Only methods can be in the class, and they must all be public static.

    4. You can't have conventional static methods - ones that don't include a this argument aren't allowed.

    5. All methods must begin:

      public static ReturnType MethodName(this ClassName _this, ...)

    So the first argument is always the this reference.

    There is an implicit problem this creates - if you add methods that require a lock of any sort, you can't really provide it at the class level. Typically you'd provide a private instance-level lock, but it's not possible to add any private fields, leaving you with some very awkward options, like providing it as a public static on some outside class, etc. Gets dicey. Signs the C# language had kind of a bad turn in the design for these.

    The workaround is to use your Extension Method class as just a Facade to a regular class, and all the static methods in your Extension class just call the real class, probably using a Singleton.

提交回复
热议问题