C # Use of static classes

Source: Internet
Author: User

Static classes are basically the same as non-static classes, but there is a difference: static classes cannot be instantiated. That is to say, you cannot use the new keyword to create a variable of the static class type. Because no instance variable exists, you must use the class name to access the members of the static class.

static class CompanyInfo{   public static string GetCompanyName() { return "CompanyName"; }    public static string GetCompanyAddress() { return "CompanyAddress"; }    //...}

Like all class types, When you load a program that references a static class, the. NET Framework Common Language Runtime (CLR) loads the type information of the static class. The program cannot specify the exact time for loading static classes. However, you can ensure that the class is loaded before the class is referenced for the first time in the program, initialize the field of the class, and call its static constructor. The static constructor is called only once. during the lifetime of the application domain where the program resides, the static class remains in the memory. Static classes can be used as containers for these method sets without obtaining or setting any internal instance fields. For example, in the. NET Framework class library, some methods in the static class system. Math only perform mathematical operations, without the need to store or retrieve data specific to a specific math class instance.

The main feature of a static class: it only contains static members. It cannot be instantiated. It is sealed. It cannot contain instance constructors. Creating a static class (a) is basically the same as creating a class that only contains static members and a private constructor (B). A private constructor prevents the class from being instantiated. In the case of B, it is easy to choose.

The advantage of using static classes is that the compiler can perform checks to prevent accidental addition of instance members. The compiler will ensure that such benefits will not be created.

Static classes are sealed and therefore cannot be inherited. They cannot be inherited from any class except the object. Static classes cannot contain instance constructors, but can contain static constructors. If a non-static class contains a static member that requires important initialization, you should also define a static constructor.

 

The following is an example of a static class, which contains two methods for converting back and forth between Celsius and Fahrenheit: public static class temperatureconverter {public static double celsiustofahrenheit (string temperaturecelsius) {// convert argument to double for calculations. double Celsius = double. parse (temperaturecelsius); // convert Celsius to Fahrenheit. double Fahrenheit = (Celsius * 9/5) + 32; return Fahrenheit;} public static double fahrenheittocelsius (string temperaturefahrenheit) {// convert argument to double for calculations. double Fahrenheit = double. parse (temperaturefahrenheit); // convert Fahrenheit to Celsius. double Celsius = (Fahrenheit-32) * 5/9; return Celsius ;}} class testtemperatureconverter {static void main () {console. writeline ("Please select the convertor direction"); console. writeline ("1. from Celsius to Fahrenheit. "); console. writeline ("2. from Fahrenheit to Celsius. "); console. write (":"); string selection = console. readline (); double F, c = 0; Switch (selection) {Case "1": console. write ("Please enter the Celsius temperature:"); F = temperatureconverter. celsiustofahrenheit (console. readline (); console. writeline ("Temperature in Fahrenheit: {0: F2}", f); break; Case "2": console. write ("Please enter the Fahrenheit temperature:"); C = temperatureconverter. fahrenheittocelsius (console. readline (); console. writeline ("Temperature in Celsius: {0: F2}", c); break; default: console. writeline ("Please select a convertor. "); break;} // keep the console window open in debug mode. console. writeline ("press any key to exit. "); console. readkey () ;}/ * example output: Please select the convertor direction 1. from Celsius to Fahrenheit. 2. from Fahrenheit to Celsius.: 2 please enter the Fahrenheit temperature: 20 temperature in Celsius:-6.67 press any key to exit. */

 

Static Member

Non-static classes can contain static methods, fields, attributes, or events. You can call static members in the class even if no instance of the class is created. You can always access static members by class name instead of Instance name.

No matter how many instances are created for a class, its static members have only one copy.

Static methods and attributes cannot access non-static fields and events in their contained types, and cannot access instance variables of any objects (unless explicitly transmitted in method parameters ).

 

A more common approach is to declare a non-static class with some static members, rather than declaring the entire class as a static class. Static fields have two common usage methods: one is to record the number of instantiated objects, and the other is to store values that must be shared among all instances.

Static methods can be overloaded but cannot be overwritten because they belong to a class and do not belong to any instance of the class.

Although the field cannot be declared as static const, the behavior of the const field is static in nature. Such fields belong to the type and do not belong to the type instance. Therefore, you can use classname. membername notation to access the const field like static fields. No object instance is required.

C # does not support static local variables (variables declared within the method range ).

You can declare a static class member by using the static keyword before the return type of the member, as shown in the following example.

 

public class Automobile{    public static int NumberOfWheels = 4;    public static int SizeOfGasTank    {        get        {            return 15;        }    }    public static void Drive() { }    public static event EventType RunOutOfGas;    // Other non-static fields and properties...} 

 

The static member is initialized before the first access and before calling the static Constructor (if any. To access a static class member, use the class name instead of the variable name to specify the position of the member, as shown in the following example:

Automobile. Drive ();

Int I = automobile. numberofwheels;

If the class contains static fields, provide the static constructor for initializing these fields when loading the class.

The call to a static method uses Microsoft intermediate language (msil) to generate the call command, while the call to an instance method generates the callvirt command, which also checks the Null Object reference. However, the performance difference between the two is not obvious in most cases.

 

Static classes are always located in the memory;

 

2: non-static classes are independent in the memory after being instantiated. Their variables will not be repeated and will be destroyed in time after use, so there will be no Unknown

 

.In C #, static members are sensitive and should not be used unless otherwise confirmed.;

 

3: We recommend that you use more general classes (non-static classes ).

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.