When does it make sense to use a public field?

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

    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.

提交回复
热议问题