When does it make sense to use a public field?

后端 未结 8 1333
时光说笑
时光说笑 2021-02-18 16:52

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:20

    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.

提交回复
热议问题