// Frog recommendation: static and non-static members in the class (C)
// Here is an example to demonstrate the differences between static and non-static members.
// The class members are either static or dynamic. If a member of the class is declared as static, the Member is static.
// The static member of a class belongs to the class and can be accessed without generating an instance of the class, that is, only the class name can be accessed.
// Static members are shared by all instances of the class. No matter how many instances are created for the class, a static member occupies only one area of the memory.
// The non-static members of the class belong to the class instance. Each instance that creates a class opens a region for non-static members in the memory.
// The static method can only use the static fields of the primary class, but not all the fields of the primary class.
Using system;
Class employee {
Public static decimal salary; // static field
Public string name; // non-static field
Public static void setsalary (decimal B) // static method
{
Salary = B; // correct, equivalent to employee. Salary = B. Note that the name variable cannot be accessed because it is a static method.
}
Public void setname (string N) // non-static method
{
Name = N; // correct, equivalent to this. Name = n.
}
}
Class sample
{
Public static void main ()
{
Employee. Salary = 500.0 m; // correct. The static field can be accessed by class name.
Employee. setsalary (500.0 m); // correct. The static method can be accessed by class name.
Employee E = new employee (); // create an instance of the class employee
E. Name = "frog prince"; // correct. Non-static fields must be accessed through the instance.
E. setname ("frog prince"); // It is correct and the non-static method must be accessed through the instance.
// Note that E. name cannot be written as employee. Name, that is, non-static members cannot access by class name.
// The employee. Salary cannot be written as E. Salary either. That is, static members cannot access the instance through the class.
Console. writeline ("employee name: {0}/n salary: {1} RMB ",
E. Name, employee. Salary );
}
}
//----------------------------------------------------
// Note that the above example only demonstrates the fields and methods in the class members. In fact, the class members also have attributes.
// Save this file as a static. CS file, and then type CSC static.csin the. NET command console to generate a static.exe file.
// Run static.exeto check the final result. You can try to change the program so that it can be compiled by using the csc.exe program,
// See what error will be prompted.