When does it make sense to use a public field?

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

    One scenario, at least in .NET, is interop with C APIs. You'll often declare C# or VB versions of Windows API structs, and it's common to use public fields for these because the normal reason for making fields private -- to prevent someone messing with them behind your back -- breaks down. In this case, you know that something is going to be changing the fields behind your back -- that's the whole purpose of having the struct!

    Of course you typically won't expose those unencapsulated structs to application code -- you'll treat them as private elements of the P/Invoke module, so application code still won't be dealing with the public fields.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题