Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
18
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 6 MORE ABOUT CLASSES

Accessing Static Members from Outside the Class

In the previous chapter, you saw that dot-syntax notation is used to access instance members from outside the class. Dot-syntax notation consists of listing the instance name, followed by a dot, followed by the member name.

Static members, like instance members, are also accessed from outside the class using dot-syntax notation. But since there is no instance, you must use the class name, as shown here:

Class name

D.Mem2 = 5; // Accessing the static class member

Member name

Example of a Static Field

The following code expands the preceding class D by adding two methods:

One method sets the values of the two data members.

The other method displays the values of the two data members.

class D {

int Mem1; static int Mem2;

public void SetVars(int v1, int v2) // Set the values

{Mem1 = v1; Mem2 = v2; }

Access as if it were an instance field

public void Display( string str )

{Console.WriteLine("{0}: Mem1= {1}, Mem2= {2}", str, Mem1, Mem2); }

}

 

 

 

Access as if it were an instance field

class Program {

 

 

static void Main()

 

 

{

 

 

D d1 = new D(), d2 = new D();

// Create two instances.

d1.SetVars(2, 4);

 

// Set d1's values.

d1.Display("d1");

 

 

d2.SetVars(15, 17);

 

// Set d2's values.

d2.Display("d2");

 

 

d1.Display("d1");

// Display d1 again and notice that the

}

// value of static member Mem2 has changed!

}

 

 

114

CHAPTER 6 MORE ABOUT CLASSES

This code produces the following output:

d1: Mem1= 2, Mem2= 4 d2: Mem1= 15, Mem2= 17 d1: Mem1= 2, Mem2= 17

Lifetimes of Static Members

The lifetimes for static members are different from those of instance members.

As you saw previously, instance members come into existence when the instance is created and go out of existence when the instance is destroyed.

Static members, however, exist and are accessible even if there are no instances of the class.

Figure 6-4 illustrates a class D, with a static field, Mem2. Even though Main doesn’t define any instances of the class, it assigns the value 5 to the static field and prints it out with no problem.

Figure 6-4. Static fields with no class instances can still be assigned to and read from, because the field is

associated with the class, and not an instance.

The code in Figure 6-4 produces the following output:

Mem2 = 5

Note Static members exist even if there are no instances of the class. If a static field has an initializer, the field is initialized before the use of any of the class’s static fields but not necessarily at the beginning of program execution.

115

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]