在 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

更新日期: 2020 年 6 月 22 日

7K+ 瀏覽量

開啟你的 職業 生涯

完成課程,獲得認證

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