Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้คีย์เวิร์ด new ใน C#

new ใช้สร้าง Instance ของ Array, Object, Collection

สร้าง Object ของ Class:

Calculate c = new Calculate();

สร้าง Array:

double[] points = new double[10];

สร้าง Collection:

SortedList sl = new SortedList();
List<string> myList = new List<string>();

ตัวอย่าง Copy Array

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];
        arrSource.CopyTo(arrTarget, 0);
        Console.WriteLine("Destination Array ...");
        foreach (int value in arrTarget) { Console.WriteLine(value); }
    }
}

ผลลัพธ์

Destination Array ...
5
9
1
3