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

CHAPTER 6 MORE ABOUT CLASSES

Static Function Members

Besides static fields, there are also static function members.

Static function members, like static fields, are independent of any class instance. Even if there are no instances of a class, you can still call a static method.

Static function members cannot access instance members. They can, however, access other static members.

For example, the following class contains a static field and a static method. Notice that the body of the static method accesses the static field.

class X

 

 

 

{

 

 

 

static public int A;

//

Static

field

static public void PrintValA()

//

Static

method

{

Console.WriteLine("Value of A: {0}", A);

 

}

}

Accessing the static field

The following code uses class X, defined in the preceding code:

class Program

 

{

 

static void Main()

 

{

 

X.A = 10;

// Use dot-syntax notation

X.PrintValA();

// Use dot-syntax notation

}

 

} Class name

 

This code produces the following output:

Value of A: 10

116

CHAPTER 6 MORE ABOUT CLASSES

Figure 6-5 illustrates the preceding code.

Figure 6-5. Static methods of a class can be called even if there are no instances of the class.

Other Static Class Member Types

The types of class members that can be declared static are shown checked in Table 6-2. The other member types cannot be declared static.

Table 6-2. Class Member Types That Can Be Declared Static

Data Members (Store Data)

Function Members (Execute Code)

Fields

Methods

Constants

Properties

 

Constructors

 

Operators

 

Indexers

 

Events

 

 

117

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