C # static variable and static method case study _c# Tutorial

Source: Internet
Author: User
Tags static class
The procedure is as follows:
Copy Code code as follows:

public static string E-English (string 中文版, translation results 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 () = = 中文版. 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 results. One)
{
Return gets the first Chinese word (query). FirstOrDefault (). Value);
}
throw new Exception ("parameter Error!");
}
}
Else
{
throw new Exception ("Dictionary file does not exist!");
}
}
catch (Exception)
{
throw new Exception ("Dictionary file Error!");
}
}

Analysis, the reason is that every time this method will be loaded into the yellow section of the English-Chinese dictionary, if executed 2000 times, will load 2000 times, natural slow, there is no way to run the program only once? Remember that there is a single example factory pattern in the design pattern that has been seen in the academy, The use of static variables seems to resolve, instance validation:
First define a class:
Copy Code code as follows:

Class Translation {
public static XDocument English-Chinese Dictionary content = english-Chinese dictionary initialization ();
Public XDocument constructs the contents of English-Chinese dictionaries;
Public translation ()
{
Construct the content of English-Chinese dictionary = English-Chinese dictionary initialization ();
}
public static XDocument English-Chinese Dictionary initialization ()
{
if (file.exists (English-Chinese dictionary file))
{
Return Xdocument.load (English-Chinese dictionary file);
}
Else
{
throw new Exception ("English-Chinese dictionary file does not exist!");
}
}
}

Main program:
Copy Code code as follows:

var one = translation. Content of English-Chinese dictionary;
var two = translation. Content of English-Chinese dictionary;
if (one==two)
{
MessageBox.Show ("Same");
}
Else
{
MessageBox.Show ("different");
}
one = new Translation (). Construct the content of English-Chinese dictionary;
two = new Translation (). Construct the content of English-Chinese dictionary;
if (one = = two)
{
MessageBox.Show ("Same");
}
Else
{
MessageBox.Show ("different");
}

Results:

The analysis is as follows:
Whether the use of static translation. English-Chinese dictionary content, or new translation (). Construct the content of English-Chinese dictionaries, they all call the English-Chinese Dictionary initialization (), but the values in the static variable will only be initialized once, each subsequent access is the last processed value, so the first display of the result is the same, that is, one, The value of the two is actually one, and the second two is actually the first-initialized value, and the constructor of the class initializes the variable each time, and naturally the result is different.
For example (reproduced below):
Copy Code code as follows:

Class Program
{
static void Main (string[] args)
{//output undefined static variable, the result is 0; it also shows that the variable system with no initial value in C # is automatically assigned 0
Console.WriteLine (SORT.I);
Static variable access method (class name. Static variable name), but also can operate static variables externally, visible static variables are not mysterious;
SORT.I = 5;
Output 5
Console.WriteLine (SORT.I);
You can also use the constructor to initialize the static variables, uh
Sort sorttest = new sort ();
The assignment in the output constructor is 3;
Console.WriteLine (SORT.I);
}
}
Class sort
{
public static int i;
Public sort ()
{
i = 3;
}
}

Summary: When accessing static variables inside a class, you can use the static variable name directly, not in the way of (class name. Static variable name),
In addition to static variables, there are static class instances, as well as static methods. But the usage is very similar;
such as: public static void Myfun () {}//static method
private static Random myrandom=new Random (); Static class instance
It is sometimes declared as a private static variable in order for it to be initialized only once. This saves memory space
But you want it to be inaccessible outside, so use the private access qualifier to get it done.
private static: Secure and space-saving.
Example: If you want to generate a set of random numbers each time the class is instantiated, but to generate random numbers is to use a class, that is, random, this class is not a static class, it is to produce an instance, with the resulting instance to generate a random number, but if each class instantiation of the generation of a random instance, That memory space is a huge waste, so you can use:
private static Random myrandom=new Random ();
So each time the class is instantiated, it uses the same random instance myrandom to generate the random number
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.