c#: what is the point in having a purely public pr

2019-07-24 07:35发布

问题:

Possible Duplicates:
Should I use public properties and private fields or public fields for data?
Property(with no extra processing) vs public field

What is the point in having a property inside a class that simply get and sets a member variable?

What practical difference would be there to just making the variable public?

回答1:

I think similar questions have been answered on many occasions, but basically it gives you the option of adding error checking/etc validation to your property without changing the public interface.

There's also some good information here, the following quote probably answers your question best:

A property communicates the idea of "I will make a value available to you, or accept a value from you." It's not an implementation concept, it's an interface concept. A field, on the other hand, communicates the implementation - it says "this type represents a value in this very specific way". There's no encapsulation, it's the bare storage format. This is part of the reason fields aren't part of interfaces - they don't belong there, as they talk about how something is achieved rather than what is achieved.



回答2:

Ease of maintenance... you can log assignments, add validation, etc., without breaking existing callers.



回答3:

You can't databind to public variables. Only public properties.



回答4:

If you ever want to change the way the method is accessed, just changing the property is much easier than going through all of your code to find it. Also, you could make the property virtual, change the underlying data type easily, or use a Settings variable so that it's saved and recalled automatically. I had a similar question myself.



回答5:

Properties allow future expansion in accessors and getters (validation, eventing, etc).

You can also make a property virtual, whereas a field cannot be.

The IL for calling fields is different to that of properties, so if you change a field to a property later on, existing compiled calling code will break.



回答6:

The point is that caller of your class do not know what field the property gets/sets, whether it's calculated, fetched from somewhere, or whether messing with it causes and update/change to the state of you class instance. With a simple field call none of these are an option.