简体   繁体   中英

What is the advantage of using Properties over private fields and get/set methods?

I have been programming classes recently and using private fields and get/set methods to access these private fields, A friend suggested to me that I use Auto Implemented properties as It would save me time programming. I was wondering what the primary differences between these two methods were and whether Auto Implemented properties keep the value of a "field" private at run-time.

For example my friend said I should use this:

public int MyProperty { get; set; }

Previously I was using something similar to this:

private int field;

public void setField(int i)
{
    field = i;
}
public int getField()
{
    return field;
}

Not only is it a better design to prevent direct access to fields, which is arguable, also the framework prefers properties over fields (and methods in some situations) for a number a things.

One of them is data binding. You can't data bind to a field, only to a property. Also, it allows you to set access modifiers to allow reading, but not writing a property for example.

Properties are also easier to write than your Java style properties. In the end the code is the same (since properties become methods eventually), but for you as a coder, it is much easier.

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