(原創) 如何動態建立二維陣列(多維陣列)? (.NET) (C#)

Abstract
C++不能用new直接動態建立二維陣列,但在C#可以了!!

Introduction
(原創) 如何動態建立二維陣列(多維陣列)? (高級) (C++)中,我們發現C++無法用

int **ia = new int[sizey][sizex];



int *ia[sizex] = new int[sizey][sizex];


動態建立二維陣列,但在C#可以了!!

 1/* 
 2(C) OOMusou 2007 http://oomusou.cnblogs.com
 3
 4Filename    : ArrayDynamicTwoDim.cs
 5Compiler    : Visual Studio 2005 / C# 2.0
 6Description : Demo how to dynamic allocate 2 dim array
 7Release     : 02/25/2007 1.0
 8*/

 9using System;
10
11class Foo {
12  static void func(int[,] ia) {
13    for (int y = 0; y != ia.GetLength(0); ++y) {
14      for (int x = 0; x != ia.GetLength(1); ++x) {
15        Console.Write("{0} ",ia[y,x]);
16      }

17      Console.WriteLine();
18    }

19  }

20
21  public static void Main() {
22    const int sizex = 3;
23    const int sizey = 2;
24    int[,]ia = new int[sizey,sizex];
25    
26    for(int y = 0; y != sizey; ++y) {
27      for(int x = 0; x != sizex; ++x) {
28        ia[y,x] = y + x;
29      }

30    }

31    
32    func(ia);
33  }

34}


執行結果

0 1 2
1 2 3


24行

int[,]ia = new int[sizey,sizex];


使用了new動態動態建立了二維陣列,這是一個很直觀的語法,至於int [,] ,這是C#二維陣列的宣告方式,有別於C++,代表C#是『真正』支援二維陣列。

12行

static void func(int[,] ia)


也不需要用pointer to pointer了,直接宣告一個二維陣列型態傳入即可,但這樣是傳進整個陣列嗎?在.NET,陣列屬於reference type,所以雖然語法看起來是value type,但骨子仍是傳pointer進去而已,C#是一個大量使用syntax sugar的語言。

Conclusion
C#身為晚C++多年的後輩,果真對C++多有改進,大幅降低語法本身的複雜度,可大幅降低學習曲線。

See Also
(原創) 如何動態建立二維陣列(多維陣列)? (C/C++) (C)
(原創) 如何動態建立二維陣列(多維陣列)? (C/C++)

posted on 2007-02-25 14:35  真 OO无双  阅读(18721)  评论(6编辑  收藏  举报

导航