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

CHAPTER 6 MORE ABOUT CLASSES

Instance Class Members

Class members can be associated with an instance of the class or with the class as a whole. By default, members are associated with an instance. You can think of each instance of a class as having its own copy of each class member. These members are called instance members.

Changes to the value of one instance field do not affect the values of the members in any other instance. So far, the fields and methods you’ve seen have all been instance fields and instance methods.

For example, the following code declares a class D with a single integer field Mem1. Main creates two instances of the class. Each instance has its own copy of field Mem1. Changing the value of one instance’s copy of the field doesn’t affect the value of the other instance’s copy. Figure 6-2 shows the two instances of class D.

class D

{

public int Mem1;

}

class Program

{

static void Main()

{

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

d1.Mem1 = 10; d2.Mem1 = 28;

Console.WriteLine("d1 = {0}, d2 = {1}", d1.Mem1, d2.Mem1);

}

}

This code produces the following output:

d1 = 10, d2 = 28

Figure 6-2. Each instance of class D has its own copy of field Mem1.

112

CHAPTER 6 MORE ABOUT CLASSES

Static Fields

Besides instance fields, classes can have what are called static fields.

A static field is shared by all the instances of the class, and all the instances access the same memory location. Hence, if the value of the memory location is changed by one instance, the change is visible to all the instances.

Use the static modifier to declare a field static, as follows:

class D

 

{

 

 

 

int Mem1;

// Instance field

static int Mem2;

// Static field

 

 

 

} Keyword

 

For example, the code on the left in Figure 6-3 declares class D with static field Mem2 and instance field Mem1. Main defines two instances of class D. The figure shows that static field Mem2 is stored separately from the storage of any of the instances. The gray fields inside the instances represent the fact that, from inside an instance method, the syntax to access or update the static field is the same as for any other member field.

Because Mem2 is static, both instances of class D share a single Mem2 field. If Mem2 is changed, that change is seen from both.

Member Mem1 is not declared static, so each instance has its own distinct copy.

Figure 6-3. Static and instance data members

113

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