Frog Frog Recommended: Static members and non-statistists in the class (C # version)

zhaozj2021-02-16  62

// Frog Recommendation: Static members and non-static members (C # Edition) // below I write an example to demonstrate the distinguished member and non-static members or static, or dynamic If a member of the class is stated as static, the member is a static member. // The static member of the class belongs to the class. You don't have to generate an instance of the class. You can access it, just use the class name to access // static member for all instances of the class, regardless of how many instances of this class, A static member only plays only a zone in memory. The non-static member of the class belongs to the instance of the class. Each time you create a class, you have opened a zone // static method for non-static members in memory. Static fields of the class, rather than static methods can access all fields of the class.

Class Employee {Public Static Decimal Saling; // Static field public string name; // Non-static field public static void setsalary (decimal b) // static method {SALARY = B; // correct, equivalent to EMPLOYE.SALARY = B Note that the Name variable cannot be accessed here 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.0m; // correct, static field can access Employee.SetSalary (500.0m) by class name; // correct, static method can access Employee E = New Employee (); // Establishing an instance of EMPLOYEE E.NAME = "Frog Frog Prince"; // Correct, non-static field must access E.SetName by instance ("Frog Frog Prince"); // Correct, Non The static method must be accessed by instance // Note that E.NAME cannot be written as an EMPLOYE.NAME, ie non-statist members cannot be accessed by class name // EMPLOYE.SALARY cannot be written into E.SALARY, ie static members cannot access Console .Writeline: {0} / n salary: {1} yuan ", E.NAME, EMPLOYE.SALARY);}} // ----------------- --------------------------------- / / Pay attention to the above example only demonstrate the class member. Fields and methods, actually attributes, etc., there is no presentation here. / / Save this file into static.cs file, then knock in the .NET command console, csc static.cs will generate one in the current directory. Static.exe file // Run static.exe will see the result, you can try the change program to let the static method access to a non-static field, then compile with the CSC.exe program, // See if you will prompt, Ha ha.

转载请注明原文地址:https://www.9cbs.com/read-17368.html

New Post(0)