Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khởi tạo (Initialization) vs Khởi tạo thể hiện (Instantiation) trong C#

Initialization (Khởi tạo giá trị)

Gán giá trị khi khai báo biến:

int val = 50;

Mảng cần new:

int[] arr = new int[] { 1, 2, 3 };

Instantiation (Khởi tạo thể hiện/instance)

Tạo object mới từ class bằng new:

Student s1 = new Student();
Student s2 = new Student();

So sánh

Khía cạnhInitializationInstantiation
Đối tượngBiến (value type, reference)Object (reference type/class)
Từ khóaCó thể không cần newLuôn cần new (trừ singleton/pool)
MảngCần new (trừ array initializer)Là một dạng instantiation
StructKhởi tạo giá trịnew gọi constructor (có thể bỏ qua)

Ví dụ kết hợp:

// Declaration + Instantiation + Initialization
List<int> list = new List<int>() { 1, 2, 3 };
//        ^declaration  ^instantiation  ^initialization (collection initializer)