简体   繁体   中英

Why do I need to use get and set?

I have a code segment:

public class MyClass
{
    private string _myProperty;

    public string MyProperty
    {
        get
        {
            return _myProperty;
        }

        set
        {
            _myProperty = value;
        }
    }
}

What is the point here? I could have declared the _myProperty string as public and any of my class objects will be able to directly access them and get or set the value.

Instead, we are making _myProperty private and the using get and set to access them, using the class object.

In either case, the class object is able to access them and the result is always same.

So why use this approach? Is that only because I can implement few constraints in setter?

Apart from that what harm will making member variables public cause? In this example I could expose _myProperty as public instead of restricting it to this class only by making it private, as OOP would suggest.

No, the result isn't always the same.

  • Try binding to a public field (or doing anything else which uses reflection and expects properties)
  • Try passing a property by reference (you can't)
  • Try later deciding you want logging etc and finding that when you change it to a property, you lose both source and binary compatibility.

Read the article I wrote on this a while ago...

Note that as of C# 2 your code can be a lot shorter though:

public class MyClass
{
    public string MyProperty { get; set; }
}

The field _myProperty is an implementation detail—it tells the compiler you want some storage for a string reference and to give it that name. The get/set methods are part of the property of the object, which abstracts how the MyProperty property is implemented. So, say, if you want to change how the string is stored/retrieved, 3rd-party dependants don't have to re-compile.

You can also use automatic properties to do this for you:

public string MyProperty {get; set;}

If you just declare variables as Public , these are not actually Properies. Many of the functionalities that use reflection will not work, in particular DataBinding, Serialization and so on.

Occasionally I get lazy and do this, particularly when working in VB.Net pre v4 as there are no auto properties, and always regret it and go back to write the properties in properly.

It is especially important to use properties if your class is to be consumed by code written by developers other than yourself, as they may well have problems with the limitations imposed by not coding full properties.

It's important to note that while it is often helpful for classes to wrap fields in properties, it is often counterproductive for structures to do so. Many of the recommended limitations on the use of structures stem from a presumption that all struct fields will be wrapped in properties. If the semantics of a struct provide that:

  1. Its state is completely defined by a fixed number of parameters, all of which are publicly exposed for reading.
  2. Those parameters may be freely assigned any combination of values that are legal for their respective types.
  3. The default instance of the struct is specified as having all parameters initialized to the default values of their respective types.

then exposing fields would expose the "inner workings" of the data type, but such exposure would not preclude any meaningful future changes to the data type which would not already be excluded by the spec . All fields of all structs that are stored in modifiable locations are always exposed for mutation, even if the only means of mutation is a bulk copy of all public and private fields from one instance to another. If the semantics of a struct require that code be able to create an instance whose defining parameters have any combination of values, without restriction, exposing a struct's fields directly won't allow single-threaded code to do anything which it couldn't do more slowly without such access. The only things exposing the fields will allow code to do which it wouldn't be able to do otherwise are:

  1. execute faster
  2. express its intention more clearly
  3. have defined semantics in multi-threading scenarios where the semantics would otherwise be murky
I don't really see much benefit to requiring consumers of a type to run slower, be written awkwardly, and have murky multi-threading semantics.

Note that if there were a policy against having structs with properties that mutate 'this', rather than a policy of encapsulating all struct fields, then a statement like:

myArraySegment[3] = 9;

would be rejected even if the language allowed property setters to be called on read-only structs (with a presumption that the purpose would be for things like

 myArraySegment[3] = 9; 

which would be understood as accessing the array to which myArraySegment holds a reference).

As you said the main reason for properties is validation. Every class has this responsibility to keep their memebers safe and _myProperty is a member of MyClass. The .Net's way for implementing this responsibility is propety. in Java you have to define two methods: SetMyPropety and GetMyProperty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM