Our goal: to write the C # code as efficiently, more robust, and easier to maintain as possible.
Principle One: Use attributes (property) as much as possible, rather than data members (field).
Always use properties instead of the accessible data members.
For the following reasons, use attributes, not members, as much as possible when designing your class.
1,. NET support for attributes is far greater than the support of members, you can data binding properties, design-time description, and many other data members are not supported content. Look at the properties panel in. NET, you will understand.
2, data security detection;
property is essentially two functions, just because of the special syntax of C #, but we can access it like a member. So we can add more flexible content to the property design and manage the attributes. The detection of attribute data is one of them.
In the case of data detection, if you find that the data does not meet the conditions, it is best to throw out the form of an exception, do not set the default value, this is a very dangerous thing. For example:
public string Name{
get{
if(this._Name==null){
return “NoName”;
}else{
return this._Name;
}
}
set{
if(value==null){
this._Name = “NoName”;
}else if(value.Length<=10) {
this._Name = value;
}else{
this._Name = value.SubString(0,10);
}
}
}
Looks pretty good, doesn't it? Please modify your code immediately, the above code is very dangerous! Or you do not understand that the data is clearly safe to detect, why is it dangerous? Imagine a situation where there are two instances of O1 and O2, O1 's name is null, and we do something like this: O2. Name = O1. Name;
What was the result? O2. Name is "NoName", and in essence, O1 is not equal to the name of O2. This can cause a lot of trouble to run the program later. In the form of throwing an exception, resolve the problem when the data does not meet the condition.