When does it make sense to use a public field?

后端 未结 8 1234
北恋
北恋 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:12

    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.

提交回复
热议问题