In C #, we expose the Property for a private field to implement data protection encapsulation. It is estimated that everyone has had a boring experience of adding Property to classes with large data volumes; or the private field and the name of one of the properties have changed, and the corresponding item name has not been adjusted, which may be under long-term development and maintenance in the future, this may cause imperceptible errors. In fact, C # allows us to define and operate a class field by using a simple attribute writing method. For example, CarName002 in the following code.
public class Car
{
private string carName001;
public string CarName001
{
get
{
return this.carName001;
}
set
{
this.carName001 = value;
}
}
public string CarName002
{
get;
set;
}
}
Attribute abbreviation internal implementation
For implementation, it is estimated that many people know that this is an auxiliary field generated by CLR internally. Let's verify it. Let's take a look at the above example of IL code:
I can see that a field named <CarName002> k_BackingField is not defined. Double-click to get more details:
This makes it clear that this is a private instance field. System. Runtime. CompilerServices. CompilerGeneratedAttribute indicates that this is generated by the compiler.
Subsequent Problem Analysis 1
Does this shorthand property correspond to an internal field with the same name? This is still a common question. From the perspective of the IL code, they correspond to different fields and have no corresponding relationship. Let's test it as follows:
Fields with the same name (Case Insensitive) are defined:
Public class Car
{
Private string carName001;
Private string carName002;
Public string CarName001
{
Get
{
Return this. carName001;
}
Set
{
This. carname001 = value;
}
}
Public String carname002
{
Get;
Set;
}
Public String getcarname002 ()
{
Return this. carname002;
}
}
In the main method:
Car car1 = new car ();
Car1.carname002 = "002 ";
System. Console. writeline ("Private carname002 value is" + car1.getcarname002 ());
System. Console. Readline ();
Subsequent Problem Analysis 2
If I need an attribute to be read-only externally, how can I modify its value for the class itself? Define get and set modifiers respectively.
public string CarName002
{
get;
private set;
}
In summary, attribute abbreviations make it much easier, but note the following:
1. Start with specific requirements. For example, attribute abbreviations cannot be added to complex logic.
2. We need to take care of the coding habits of ourselves and others and the consistency of the project code style from the usage habits and specific project style.