C# static methods and static fields, properties

1. Fields or methods modified with the keyword static become static fields and static methods, such as public static int num = 1;
2. Static fields belong to classes and are used by classes. Non-static fields belong to objects and can only be used exclusively by specific objects.
3. C# strictly stipulates that non-static fields can only be accessed through objects, and static fields can only be accessed through classes.
4. Use static members when they are not related to the instance of the class but only related to the class (for example, the mathematical calculation method of the Math class does not need to create multiple instances)
5. The use of static members can avoid introducing an object structure when creating an object 6, C# static methods and
properties are all loaded into memory when the program starts, regardless of whether these methods and properties are used later. Even if no one accesses the program, this part of the memory will still not be released. Also, the data of the static properties seen by all visitors is almost the same. For example, when user A sets the attribute UserName, when user B accesses it, The resulting UserName is still the one set by the A user.
7. Note that static connection objects cannot be used. Staticization leads to a large number of concurrent use of the same connection pool, and the number of connection pools is limited, which will cause the database connection pool to reach the maximum value and cannot continue to access the website.

 

It is best to use private restrictions for fields, and then use public properties to check assignments. It can be considered that fields are used internally, and only properties restricted by public can be accessed and checked before assignment.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324513631&siteId=291194637