Public Property Definition
What are the benefits of defining a property for a object instead of giving direct access to the private variable?
Instead of :
public class A
private _x as integer = 0
Public property X() as integer
Get
return _x
End Get
Set(ByVal value As integer)
_x = value
End Set
End Property
end class
Why we can't do following:
public class A
public _x as integer = 0
end class
What are the benefits?
One benefit is that a number of frameworks look for properties of a class for binding purposes, not fields. So directly exposing the _x
field will cause some headaches when you're wondering why a framework isn't setting the value as you might expect.
Also due to encapsulation you can change what happens when calling code interacts with the field. Hiding the field behind a property getter/setter allows you to perform additional actions like triggering when the value changes, updating other internal state, or changing the implementation entirely so it's just a wrapping call to a child object.
The main reason is that you can add behavior (logging, validation, database backend, etc.) to the property later without changing the ABI (Application Binary Interface). If you had defined it as a field, then wanted to add behavior, you would need to change to a property (or a method). Either of these would require other code to be recompiled (and modified, if you went the method route).
精彩评论