When does it make sense to use a public field?

后端 未结 8 1205
北恋
北恋 2021-02-18 17:02

This is a question I have had for a while now:

When does it make sense to expose a field publicly like so?

public class SomeClass()
{
   public int backi         


        
8条回答
  •  伪装坚强ぢ
    2021-02-18 17:32

    One of the scenarios when public field is a better choice is providing constants of your class.

    For example, see:

    public const double PI
    

    defined in System.Math.

    This approach is favored because it explicitly informs consumers of your class, that this member does not include any logic, validation or any other state-related operation, thus can be used in whatever context you want.

    The other one I can think of, is when you need classes as containers for simple operations (or just for passing the large number of params to a method), as an example see System.Windows.Point. In most cases, these containers are modeled as structs though.

提交回复
热议问题