When does it make sense to use a public field?

后端 未结 8 1206
北恋
北恋 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.

提交回复
热议问题