When does it make sense to use a public field?

后端 未结 8 1340
时光说笑
时光说笑 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:14

    I think it makes sense when you want to group some variables/objects (kind of like a C struct). For example:

    class Pixel {
      public int x;
      public int y;
      Color c;
      // Other Pixel related information
    }
    

    As there are no methods, nothing breaks if a wrong value is used and it nicely puts these variables together.

提交回复
热议问题