在 C# 中使用 new 關鍵字


使用 new 關鍵字建立陣列例項。new 運算子用於建立物件或例項化物件。在此示例中,使用 new 為類建立了一個物件。

以下是一個示例。

Calculate c = new Calculate();

此外,還可以使用 new 關鍵字建立陣列例項。

double[] points = new double[10];

new 關鍵字還用於建立集合物件。

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

我們看一個示例。

示例

 即時演示

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() method
      arrSource.CopyTo(arrTarget,0 );

      Console.WriteLine("Destination Array ...");
      foreach (int value in arrTarget) {
         Console.WriteLine(value);
      }
   }
}

輸出

Destination Array ...
5
9
1
3

更新時間: 22-Jun-2020

7K+ 瀏覽

開啟你的 職業生涯

完成本課程以獲得認證

開始學習
廣告
© . All rights reserved.