Topic: In this article I have a relationship between subordinate (properties) and fields in C #. First of all, the properties mentioned here are usually said to contain get, or set accessor properties, not attributes. When we write a program, most of the entity classes are used, and the entity class is generated, and we all declare some of the general properties or the automatically implemented properties. As for which attribute to choose, or whether it can be directly replaced by a field?
Differences between general and automatic implementations of properties:
A complete general attribute is composed of the following parts:
1: Private field, used to store variables (backing store), this field is private, so that it can only be assigned through attributes.
private string _sName;
2: A get accessor, which is responsible for reading data, for returning field values or for evaluating and returning field values. Terminates with return or throw statement. It can contain simple logical processing, such as data validation, and so on.
get
{
//电脑价格,如果小于零,则返回0,说明数据不正常
return _computerPrice >= 0 ? _computerPrice : 0;
}
Description: Get accessor is read data, all do not modify the property state in the code block. The following code is not recommended.
private string _sName;
public string sName
{
get
{return (_sName+"");}
}
3: A set accessor that assigns a value to a property, similar to a method with a return type of void, that can contain logical processing, such as a result that can be computed with the default value.
General Attribute Categories:
1: By Access modifier: You can mark the property as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access properties.
2: Attributes can also be marked as static properties, instance properties, virtual properties, abstract properties, it should be noted that if the property has been marked as static, then can not be followed by virtual (virtual), abstraction (abstract), rewrite (override) mixed.
3: The same property if only the get accessor is included, we call it a read-only property, if it contains only a set accessor, a writable property, and if there is got and a set accessor, we call it a readable writable property.
What are the properties that are automatically implemented?
An automatically implemented property makes a property declaration more concise when no other logic is needed in the property accessor. When you declare a property as shown in the following example, the compiler creates a private, anonymous fallback field that can only be accessed through the property's get and set accessors.
public string sName
{
get;
set;
}