C # example of static variables and static methods

Source: Internet
Author: User

I wrote a small program for English-Chinese dictionary translation, and found that it was slow to call thousands of times. The program is as follows:

 

Public static string English-Chinese (string English, one or more translation results) {string English-Chinese dictionary = settings. default. dictionary directory + "haou_dict.xml"; try {If (file. exists (English-Chinese dictionary) {xdocument dictionary = xdocument. load (English-Chinese dictionary); var query = from P in dictionary. descendants ("name") Where p. value. tolower () = English. tolower () select P. parent. element ("content"); If (query. firstordefault () = NULL) {return NULL;} else // can translate {If (one or more = Translation results. multiple) {Return query. firstordefault (). value. trim ();} else if (one or more = Translation results. one) {return to get the first Chinese character word (query. firstordefault (). value);} Throw new exception ("parameter error! ") ;}} Else {Throw new exception (" the dictionary file does not exist! ") ;}} Catch (exception) {Throw new exception (" dictionary file error! ");}}

The reason is that the English-Chinese dictionary at the yellow bar is loaded every time this method is called. If it is executed 2000 times, it will be loaded 2000 times, which is naturally slow, is there any way to load data only once when the program is running? I think that there is a singleton factory model in the design model that I have seen in Shang xuexiang. Using static variables, it seems to be able to solve the problem. instance verification:

First define a class:

Class translation {

Public static xdocument English-Chinese dictionary content = English-Chinese dictionary initialization (); Public xdocument constructs English-Chinese dictionary content; Public translation () {constructs English-Chinese dictionary content = English-Chinese dictionary initialization ();} public static xdocument English-Chinese dictionary initialization () {If (file. exists (English-Chinese dictionary) {return xdocument. load (English-Chinese dictionary file);} else {Throw new exception ("English-Chinese dictionary file does not exist! ");}}

}

Main Program:

VaR one = translation. english-Chinese dictionary content; var two = translation. english-Chinese dictionary content; If (one = two) {MessageBox. show ("same");} else {MessageBox. show ("different");} One = new translation (). construct the English-Chinese dictionary; two = new translation (). construct the English-Chinese dictionary; If (one = two) {MessageBox. show ("same");} else {MessageBox. show ("different ");}

Result:

 

The analysis is as follows:

Whether static translation is used. english-Chinese dictionary content, or new translation (). when constructing the English-Chinese dictionary content, they all call the English-Chinese dictionary initialization (), but the values in the static variables will only be initialized once. Each subsequent access will be the last processed value, therefore, the results displayed for the first time are the same, that is, the value of one and two is actually one, and the value of the second two access is actually the value after the first one initialization; the class constructor will reinitialize the variable each time. Naturally, the result is different.

For example, (the following content is reprinted ):

 

Class program {static void main (string [] ARGs) {// outputs an undefined static variable and the result is 0. It also describes that, the variable system without initial values in C # is automatically assigned 0 console. writeline (sort. i); // static variable access method (class name. static variable name), and you can also operate static variables externally. It can be seen that static variables are not mysterious; sort. I = 5; // output 5 console. writeline (sort. i); // You can also use the constructor to obtain the initial values of static variables. Oh, sort sorttest = new sort (); // value assignment 3 in the output constructor; console. writeline (sort. i) ;}} class sort {public static int I; Public sort () {I = 3 ;}}conclusion: When you access static variables within the class, directly use the static variable name, not used (class name. static variable name). In addition to static variables, there are also static class instances and static methods. however, the usage is similar;
For example, public static void myfun () {}// static method
Private Static random myrandom = new random (); // The reason why a static class instance is declared as a private static variable is that it is initialized only once. this saves the memory space and makes it inaccessible outside, so you can use the private access qualifier. private Static: secure and space-saving. for example, if you want to generate a group of random numbers at the time of each instantiation class, but to generate a random number, you need to use a class, namely, random. This class is not a static class and generates instances, the generated instance is used to generate random numbers. However, if a random instance is generated during each class instantiation, the memory space is a huge waste, so you can use: private Static random myrandom = new random (); in this way, the same random instance myrandom is used to generate random numbers every time the class is instantiated.

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.