Can There Be Private Extension Methods?

后端 未结 6 1511
Happy的楠姐
Happy的楠姐 2021-01-07 16:01

Let\'s say I have a need for a simple private helper method, and intuitively in the code it would make sense as an extension method. Is there any way to encapsulate that hel

6条回答
  •  日久生厌
    2021-01-07 16:40

    I believe the best you can get in general case is internal static class with internal static extension methods. Since it will be in your own assembly the only people you need to prevent usage of the extension are authors of the assembly - so some explicitly named namespace (like My.Extensions.ForFoobarOnly) may be enough to hint to avoid misuse.

    The minimal internal restriction covered in implement extension article

    The class must be visible to client code ... method with at least the same visibility as the containing class.

    Note: I would make extension public anyway to simplify unit testing, but put in some explicitly named namespace like Xxxx.Yyyy.Internal so other users of the assembly would not expect the methods to be supported/callable. Essentially rely on convention other than compile time enforcement.

提交回复
热议问题