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

Sử dụng từ khóa new trong C#

Dùng new để tạo instance của mảng. Toán tử new tạo đối tượng hoặc khởi tạo đối tượng. Ví dụ tạo object cho lớp:

Calculate c = new Calculate();

Cũng dùng new tạo instance mảng:

double[] points = new double[10];

Dùng new tạo object collection:

SortedList sl = new SortedList(); // SortedList
List myList = new List(); // List

Ví dụ:

Ví dụ

using System;

class Program {
    static void Main() {
        int[] arrSource = new int[4];
        arrSource[0] = 5;
        arrSource[1] = 9;
        arrSource[2] = 1;
        arrSource[3] = 3;
        int[] arrTarget = new int[4];
        // CopyTo()
        arrSource.CopyTo(arrTarget, 0);
        Console.WriteLine("Mảng đích...");
        foreach (int value in arrTarget) {
            Console.WriteLine(value);
        }
    }
}

Kết quả

Mảng đích...
5
9
1
3