C # example of static variables and static methods

Source: Internet
Author: User

The procedure is as follows: Copy codeThe Code is as follows: public static string english-Chinese (string english, the translation result is one or more)
{
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 be translated
{
If (one or more = Translation results. Multiple)
{
Return query. FirstOrDefault (). Value. Trim ();
}
Else if (one or more = translation result. One)
{
Return to obtain 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:Copy codeThe Code is as follows: class translation {
Public static XDocument English-Chinese dictionary content = English-Chinese dictionary initialization ();
Public XDocument: Construct the English-Chinese dictionary;
Public translation ()
{
Construct an English-Chinese dictionary = Initialize an English-Chinese dictionary ();
}
Public static XDocument English-Chinese dictionary initialization ()
{
If (File. Exists (English-Chinese dictionary ))
{
Return XDocument. Load (English-Chinese dictionary file );
}
Else
{
Throw new Exception ("the English-Chinese dictionary file does not exist! ");
}
}
}

Main Program:Copy codeThe Code is as follows: 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 (). Construct the English-Chinese dictionary content;
Two = new translation (). Construct the English-Chinese dictionary content;
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 ):Copy codeThe Code is as follows: class Program
{
Static void Main (string [] args)
{// Output the undefined static variable and the result is 0. It also shows that the variable system automatically assigns 0 to the variable without an initial value in C #.
Console. WriteLine (sort. I );
// Method for accessing static variables (class name. static variable name). 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 constructors to obtain the initial values of static variables.
Sort sortTest = new sort ();
// Value 3 in the output constructor;
Console. WriteLine (sort. I );
}
}
Class sort
{
Public static int I;
Public sort ()
{
I = 3;
}
}

Summary: when accessing static variables within a class, you can directly use the static variable name instead of (class name. static variable name,
In addition to static variables, there are also static class instances and static methods, but the usage is similar;
For example, public static void myFun () {}// static method
Private static Random MyRandom = new Random (); // static class instance
Sometimes declared as a private static variable to only initialize it once. This saves memory space.
However, if you want to make it inaccessible externally, 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 for each class instantiation.

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.