What is the best practice for using public fields?

后端 未结 11 1227
旧时难觅i
旧时难觅i 2020-12-03 03:07

When I write a class I always expose private fields through a public property like this:

private int _MyField;
public int MyField
{ get{return _MyField; }


        
相关标签:
11条回答
  • 2020-12-03 03:35

    In general, if an type is going to be used as a data holder, it should either be:

    1. A mutable struct with exposed fields, if each of the fields will behave as a value from the standpoint of the type, and any arbitrary combination of field values will "make sense". Note that the fields holding references to mutable class types may qualify if the purpose of the fields is to hold the identity of the objects in question, rather than the contents. Structs with mutable fields got a bad reputation as a result of silly C# compilers that would interpret `SomeThing.SomeStruct.SomeField = whatever` as `tempStruct = SomeThing.SomeStruct; tempStruct.SomeField = whatever` without issuing a diagnostic, but there's no reason for programmers today to worry about such what ancient compilers would do.
    2. An immutable class or struct with non-public fields, for situations where the above do not apply, and where having to regenerate an entire data item to change one aspect thereof would not be overly bothersome.
    3. A mutable class, if references to it will not be persisted outside the entity which creates it (such references should generally never be exposed to outside code). Note that the other two options, when workable, should be vastly preferred, since a collection which uses a mutable class type as data holder (as opposed to a collection which simply stores the identities of objects but don't care what those objects represent) will often have to make a defensive copy of any object which is stored in the collection, and then make an additional defensive copy every time the object is read. Structs, whether mutable or "immutable", must be copied whenever they are stored or read back from a collection, but such copies are cheaper, for any size struct, than the defensive copies that would be required if using a mutable class.

    If there is no practical alternative to using a mutable class, the question of whether to expose public fields depends upon whether there's any foreseeable need for any version of the class to include validation logic in a property setter, and also whether the type of a member will be a value type or class type. If Bounds is a public field of type Rectangle, an expression like SomeClass.Bounds.Width can access the Width of the rectangle without having to access any other members. By contrast, if Bounds were a property--even a mutable one--that expression would have to copy all four members of Bounds to a temporary structure, and then access the Width field of that.

    0 讨论(0)
  • 2020-12-03 03:37

    What is the best practice for using public fields?

    “Don’t.” See also: Should protected attributes always be banned? which concerns protected fields but what is said there is even more true for public ones.

    0 讨论(0)
  • 2020-12-03 03:38

    The answer I give is that Properties are more Refactor friendly.

    If you have an assembly with read-only fields, then change them to properties. If you have another assembly that I accessing the fields (now properties), they wont work without a compile. Fields and properties are not the same as far as the compiler is concerned.

    Back to refactoring, say you started with a property. Now you need to change where the data is coming from (you will access it from another class). If you were dealing with fields you have some hard decisions to make on how to make that happen. Properties are much more forgiving -- because you can hide logic in them.

    0 讨论(0)
  • 2020-12-03 03:41

    The best practice is to use properties for several reasons. First, it decouples the API from the underlying data structure. Second, anything built into the framework that binds to objects does to to properties, not fields.

    I'm sure there are more reasons, but those two always seem to be enough for me.

    0 讨论(0)
  • 2020-12-03 03:41

    What is the difference between a Field and a Property in C#?

    0 讨论(0)
  • 2020-12-03 03:44

    I recommend using something similar to this:

    public class Result{  
        public bool Result {  get; protected set; }
        public string Message {  get; protected set; }
    
        public Result(bool result, string message) {
            Result = result;
            Message = message;
        }
    }
    

    This way, you don't need to declare member variables, let the compiler do the work for you! The code is very clean and short, and refactoring is a breeze.

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