可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm fairly new to C#, and I think properties are a wonderful thing. So wonderful, in fact, that I can't see any real advantage to using fields, instead. Even for private fields, it seems like the flexibility and modularity that properties offer can at best save you serious headaches, and at worst have no effect at all.
The only advantage I can see for fields is that you can initialize them inline. But most of the time, you want to initialize them in the constructor, anyway. If you aren't using inline initialization, is there any reason not to use properties all the time?
Edit: Some people have brought up the need to back up properties with fields (either explicitly or automatically). Let clarify my question: Is there any reason to use fields except to back up properties? I.e., is there any time that SomeType someField;
is preferable to SomeType SomeProperty { get; set; }
?
Edit 2: DanM, Skurmedel, and Seth all gave really useful answers. I've accepted DanM's, as it is the most complete, but if someone were to summarize their responses into a single answer, I'd be happy to accept it.
回答1:
Typically, properties need a backing field unless they are simple getter/setter "automatic properties".
So, if you're just doing...
public string Name { get; set; } // automatic property
...you don't need a field, and I agree, no reason to have one.
However, if you're doing...
public string Name
{
get { return _name; }
set
{
if (value = _name) return;
_name = value;
OnPropertyChange("Name");
}
}
...you need that _name
backing field.
For private variables that don't require any special get/set logic, it's really a judgment call whether to do a private automatic property or just a field. I usually do a field, then, if I need it to be protected
or public
, I will change it to an automatic property.
Update
As noted by Yassir, if you use automatic properties, there's still a field lurking behind the scenes, it's just not something you actually have to type out. So, the bottom line is: properties don't store data, they provide access to data. Fields are what actually hold the data. So, you need them even if you can't see them.
Update 2
Regarding your revised question...
is there any time that SomeType someField; is preferable to SomeType SomeProperty { get; set; }
?
...one thing that comes to mind: If you have a private field, and (according to convention for private fields) you call it _name
, that signals to you and anyone reading your code that you are working directly with private data. If, on the other hand, you make everything a property, and (according to convention for properties) call your private property Name
, now you can't just look at the variable and tell that it is private data. So, using only properties strips away some information. I haven't tried working with all properties to gauge whether that is crucial information, but something is definitely lost.
Another thing, more minor, is that public string Name { get; set; }
requires more typing (and is a little messier) than private string _name
.
回答2:
Properties are a wonderful thing -- but there is overhead associated with property access. Not necessarily a problem, but something to be aware of.
Avoiding Overuse of Property Getters and Setters
Most people don't realize that property getters and setters are similar to methods when it comes to overhead; it's mainly syntax that differentiates them. A non-virtual property getter or setter that contains no instructions other than the field access will be inlined by the compiler, but in many other cases, this isn't possible. You should carefully consider your use of properties; from inside a class, access fields directly (if possible), and never blindly call properties repeatedly without storing the value in a variable. All that said, this doesn't mean that you should use public fields!
Source: http://dotnet.sys-con.com/node/46342
回答3:
If you want to have something readonly
you pretty much have to use a field as there is no way to tell an automatic property to generate a read-only field.
I do this quite often.
Contrived example:
class Rectangle
{
private readonly int _width;
private readonly int _height;
public Rectangle(int width, int height)
{
_width = width;
_height = height;
}
public int Width { get { return _width; } }
public int Height { get { return _height; } }
}
This means nothing inside of Rectangle can alter the width or height after construction. If one tries to the compiler will complain.
If I instead had used an automatic property with a private setter the compiler wouldn't protect me from myself.
Another reason I see is, if a piece of data doesn't have to be exposed (stay private
) why make it a property?
回答4:
Just try using a Property when using ref/out args:
someObject.SomeMethod(ref otherObject.SomeProperty);
It won't compile.
回答5:
I don't see why you'd use private autoproperties. What advantage is there to
private int Count {get; set;}
over
private int count
回答6:
While I agree with what I perceive as the "intent" in David Basarab's statement : "There is no reason to publicly expose fields," I'd like to add a slightly different emphasis :
I'd modify the quote from David above to read : "There is no reason to publicly expose fields ... outside a class ... except through the conscious choice of encapsulating the fields in Properties through which access is rigorously controlled.
Properties are not simply a "veneer" of syntax over Fields "tacked onto" C# : they are a fundamental language feature designed for good reasons including :
controlling what is exposed and not exposed outside classes (encapsulation, data hiding)
allowing certain actions to be performed when a Property is accessed or set : actions that are best expressed in the Property 'get and 'set, rather than being "elevated" to externally defined methods.
Interfaces by design cannot define 'fields : but can define Properties.
Good OO Design means making conscious choices about "state" :
local variable fields : what state is private to a method and transient : local variables typically only valid within the scope of a method body, or even with as "narrow a lifespan" as within the scope of something like a 'for loop. Of course you can regard parameter variables in a method as "local" also.
class instance fields : what state is private to a class, and has independent existence for each instance of a class, but is most likely required to be used in several places in the class.
static instance fields : what state will be a property of the class only, independent of the number of instances of the class.
state deliberately and consciously exposed "outside" the class : the key idea being that there is at least one level of indirection interposed between the class and "consumers" of the data the class exposes. The "flip side" of "exposure" is, of course, the conscious intention of hiding (encapsulating, isolating) implementation code.
a. via public properties : all aspects of this well-covered in all the other answers here
b. via indexers
c. via methods
d. public static variables are usually found in utility classes, which are often static classes.
Suggest you review : MSDN on 'Fields ... MSDN on Properties ... MSDN on Indexers
回答7:
There is no reason to publicly expose fields.
If you public expose a field you can't change the source of the information, from inline defination to configuration file without refactoring.\
You could use a field to hide internal data. I rarely favor that, I only use fields when I am doing something to hide publicly and using it in a property. (i.e. I am not using Automatic property generation)
回答8:
Fields are the only place you can store state. Properties are actually just a pair of methods with special syntax that allows them to be mapped to the get or set method depending on how they're being used: if a property modifies or accesses state, that state still has to be stored in a field.
You don't always see the fields. With C# 3 automatic properties, the field is created for you by the compiler. But it's still there. Furthermore, automatic properties have some significant limitations (e.g. no INotifyPropertyChanged support, no business logic in setters) that mean they're often inappropriate, and you need to create an explicit field and a manually defined property anyway.
As per David's answer, you're right if you're talking about an API: you almost never want to make the internal state (fields) part of the API.
回答9:
The syntax for fields is a lot quicker to write than for properties, so when it's safe to use a field (private to the class) why not use it and save that extra typing? If auto-implemented properties had the nice short concise syntax and you had to do extra work to make a plain old field, people might just start use properties instead. Also, it's a convention now in C#. That's how people think, and it's what they expect to see in code. If you do something different form the normal, you will confuse everyone.
But you could ask why the syntax for fields doesn't create an auto-implemented property instead of a field, so you get the best of both worlds - properties everywhere and a concise syntax.
There's a very simple reason why we still need to have explicit fields:
C# 1.0 didn't have all these nice features that we have now, so fields were a fact of life - you couldn't really live without them. Lots and lots of code relies on fields and properties being visibly different things. It simply cannot be changed now without breaking tons of code.
I would suspect also that there are performance implications, but perhaps that can be solved by the jitter.
So we're stuck with fields forever, and since they're there and they've taken the best syntax, it makes sense to use them when it's safe to do so.
回答10:
Fields and properties are not interchangeable. I guess what you're saying is accessing private fields through private properties. I do this when it makes sense but for the most part, it's not necessary. The JIT optimizer will inline access to a private field through a private property in most cases anyway. And wrapping a private field in a private property is not considered a breaking change anyway since private members are not a part of your interface.
Personally, I would never expose any protected/public instance fields. It's generally acceptable though to expose a public static field with a readonly modifier as long as the field type is itself immutable. This is often seen with SomeStruct.Empty static fields.
回答11:
As others have noted, you will need a private backing field for properties anyway.
Also there is a speed advantage in using fields over properties. In 99.99 % of the cases it won't matter. But in some it might.
回答12:
Speed. If a field gets set or read billions of times over the course of a simulation then you want to use a field and not a property to avoid the overhead och a sub routine call. Conforming to OO (DDD?) as far as possible, in these instances, I'd recommend resorting to fields only in class dedicated to representing some sort of "value" like person. Logic should be kept to a minimum. Rather, have a personcreator or a personservicer.
But if you have these issues then you're probably not programming c++ and not c#, aren't you?
回答13:
There are several good (partial) answers by @Seth (fields perform better, so in a private context you might as well use that to your benefit when it makes sense), @Skurmedel (fields can be readonly), @Jenk (fields can be used for ref/out). But I'd like to add one more:
You can use the streamlined initialization syntax for setting the value of a field, but not a property. i.e.:
private int x = 7;
vs
private int x { get; set; }
// This must go in the constructor, sometimes forcing you to create
// a constructor that has no other purpose.
x = 7;