Static Constructors Constructors

Một phần của tài liệu Lập trình Windows - Lập Trình C #- Lập Trình C Shap - Chương 3 potx (Trang 27 - 31)

static ConstructorsConstructors

 Static constructor được dùng để khởi đầu bất kỳ giá trị static (static data) nào hay thực thi 1 hành giá trị static (static data) nào hay thực thi 1 hành động (action) chỉ ra 1 lần duy nhất của 1 lớp.

 Được gọi tự động trước khi 1 điển hình của lớp được tạo hay bất kỳ static member nào được được tạo hay bất kỳ static member nào được tham chiếu.

 Mỗi class chỉ có thể có 1 constructor static.

 Constructor static không chứa access modifier và bất kỳ tham số nào. và bất kỳ tham số nào.

 Constructor static chỉ thực thi đúng 1 lần, bất kể có bao nhiêu đối tượng được tạo ra. có bao nhiêu đối tượng được tạo ra.

static

static ConstructorsConstructors

A static constructor can never be called directly; instead, it is executed when one of the following occurs:

An instance of the class containing the static constructor is created.

A static member of the class containing the static constructor is accessed.

In both cases, the static constructor is called first, before the class is instantiated or static members accessed. No matter how many instances of a class are created, its

static constructor will only be called once.

All nonstatic constructors are also known as instance

29

public class Bus

{ // Static constructor: static Bus()

{

System.Console.WriteLine("The static constructor invoked.");

}

public static void Drive() {

System.Console.WriteLine("The Drive method invoked."); }

}

class TestBus {

static void Main() {

Bus.Drive(); }

}

Output

The static constructor invoked. The Drive method invoked.

Output

The static constructor invoked. The Drive method invoked.

Ví dụ 1 Ví dụ 1

DestructorDestructor Destructor

Thực hiện nhiệm vụ “clean” khi đối tượng bị hủy

Trùng tên lớp và có dấu “~” phía trước

Không có tham số và access modifier

Mỗi lớp chỉ có 1 destructor class HocSinh { //... ~HocSinh() { siSo--; } }

Một phần của tài liệu Lập trình Windows - Lập Trình C #- Lập Trình C Shap - Chương 3 potx (Trang 27 - 31)

Tải bản đầy đủ (PPT)

(118 trang)