Why do we use .NET properties instead of plain old

2019-02-01 22:23发布

I understand the many benefits of providing an interface to access the members of a class indirectly. My question is: isn't that already something you can accomplish in just about any OO language using (something along the lines of)

public int NormalClass::getQuality() {
    return this->quality;
}

and

protected void NormalClass::setQuality(int q) {
    this->quality = q;
}

?

What additional benefits do .NET properties offer, beyond sheer aesthetics?

I will accept "readability" if you can make a compelling argument for it; but personally, I'm inclined to think a get/set function is more readable than a property since it is unambiguously a function as opposed to a straight-up value.

EDIT: Thanks to everybody for answering! This has been really informative for me; to sum up what I've gathered/learned from all that has been said, the following are a few conclusions I've reached so far:

  • The greatest benefits of properties come not from specific features of properties themselves, but rather from framework and IDE features which handle properties in a special way; e.g., the Properties editor, XML serialization, data binding.
  • Properties can be treated as simple values in certain convenient ways that get/set functions can't: in particular, obj.Prop++ and obj.Prop = value.
  • Properties let you get away with quick and dirty code using public members without going through the headache of implementing a bunch of get/set functions later; if you should ever need to add some logic and/or make a public member private, you can simply introduce a property and not risk breaking any old code.

Now, there is one point that's been made in 2 or 3 of the answers so far that I personally find somewhat dubious: that properties imply inexpensive read/write operations and can therefore be used in essentially the same way as simple variables. My issue with this point is that there is nothing inherent in properties that actually enforces this; it is simply how they are supposed to be used. To me, this is analogous to a "shouldBePrivate" qualifier that indicates a value should be accessed directly only by its own class, but which can still be accessed externally anyway; or a police force that patrols the streets to remind us that we should behave ourselves, but does not actually interfere when we start committing crimes (if it isn't enforced, what is it really doing for us?).

I'd be more impressed by this point if properties had some sort of built-in mechanism for ensuring read/write cheapness.

15条回答
forever°为你锁心
2楼-- · 2019-02-01 23:06

Jon Skeet has an excellent overview on his C# article blog about why properties matter. In it he explains why properties should be used over exposing public fields.

As for why to use properties instead of getter/setter methods, I would suggest the following thoughts:

  • Properties provide a cleaner, more concise syntax that is easy to understand and read.
  • Properties enable assignment expression chaining: A.x = B.y = C.z
  • Properties convey the semantics of data access clearly and consistently - consumers expect that there are no side effects.
  • Properties are recognized by many libraries in .NET for tasks such as XML serialization, WPF bindings, ASP.NET 2-way binding, and more.
  • Properties are recognized by the IDE and many visual designers and can be displayed in a property editor.
  • Properties enable support for the increment (++) and decrement (--) operators.
  • Properties can be easily differentiated from methods using reflection and allow dynamic consumers to extract knowledge about the data exposed by an object.
  • C# 3 supports automatic properties which helps eliminate boilerplate code.
查看更多
地球回转人心会变
3楼-- · 2019-02-01 23:06

Properties (specially automatic properties in .net 3.5) are more concise than setters/getters, and less lines of code == less code to maintain == less bugs.

I would say readability first, but you already said that won't count to you.. :)

查看更多
We Are One
4楼-- · 2019-02-01 23:06

Properties at the essence are get/set method pairs.

Properties are a runtime supported method of exposing a pair of get set methods that have metadata support which means they are discoverable using reflection without guessing what methods are supposed to form the accessor based on method name and signature.

The other advantage of properties is that they act like fields syntactically, and not like methods, which has the advantage of creating more clean code.

I'm inclined to think a get/set function is more readable than a property since it is unambiguously a function as opposed to a straight-up value.

Most of the time properties are inlined by the Jit engine, because they are very simple, which means most of the time properties act like fields more than they act like functions, so they are closer to how fields behave than functions.

In the case of properties it doesn't mater if there is ambiguity between a function call and field access because for the greatest part you don't pay the function call cost, property getters and setters, because of their simplicity, are high candidates for inlining, which means that cost wise the are closer to fields than function calls *.

  • Note: not all properties are cheap, but the general guidelines state that they should be as simple and lightweight as possible.
查看更多
登录 后发表回答