internal vs public in c#

前端 未结 7 1141
野趣味
野趣味 2020-11-29 04:07

I want to know the difference between the public and internal visibility modifiers.

When should we use internal on a class and

7条回答
  •  伪装坚强ぢ
    2020-11-29 05:01

    public is visible from wherever.

    internal is visible only within an assembly

    You tend to use internal only to protect internal APIs. For example, you could expose several overloads of a method:

    public int Add(int x, int y)
    public int Add(int x,int y, int z)
    

    Both of which call the internal method

    internal int Add(int[] numbers)
    

    You can then put a lot of sophistication on a method, but "protect" it using facade methods that may help the programmer to call the method correctly. (The implementation method with the array parameter may have an arbitrary limit of values, for example.)

    Also worth noting that using Reflection, any and all methods are callable regardless of their visibility. Another "hack" to control/gain access to internally hidden APIs.

提交回复
热议问题