问题
Possible Duplicate:
C# 3.0 Auto-Properties - useful or not?
My boss and I regularly argue about the benefits and disadvantages of using automatic properties.
public string Name { get; set; }
vs
private string name;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
For
I am strongly in favor of using them because I have to write less code, I find it easier to understand the class when all the fields are coded that way and just saves me a lot of time in the long run (mostly because I write a bit less code each time).
Against
He argues that they break some programming principle because the fields should reflect the state of the object and by using a property instead of a field with a property to access it, I lose that information while debugging. (Boss if you read this and it's not exactly what you mean, feel free to comment ;))
What's everyone's take on this matter?
NOTE: I have looked at the duplicate and it doesn't talk about the against points which is the point of this question. It's just people saying "I love them"/"I don't care".
回答1:
How do you give up that information? The property reflects the state of the object instead of the field - is it that big a difference?
The only time I want to have it backed by a field is if I need to do additional logic when setting it (ie: validation) or when I want to enforce a design pattern such as caching the value or singleton etc.
回答2:
Perhaps my understanding of Auto implemented properties is flawed, but if the documentation is to be bekieved, it is still backed by a property. Auto-implemented properties are a shortcut for writing boilerplate code only. The complier expands the Auto property upon compiliation, right? If you look at the IL it should show you a backing field. I believe the backing field is the property name preceded with an underscore.
So, the field does reflect the state of the object AND you don't have to write as much code. The field is just hidden in the IDE, although you should still be able to access it using reflection, if you wanted to.
回答3:
His argument is wrong (so perhaps you've mis-quoted it).
Anyway, it doesn't matter. You are exaggerating how much time you save. And with most real-world applications, you'll start off with an automatic property and eventually change it to be backed by a real field for various purposes. It's really a useless argument.
来源:https://stackoverflow.com/questions/3693428/the-case-against-automatic-properties