2013-07-26 137 views
2

我有我使用的盒子多維數組,我有一個生成它周圍的邊框代碼,就像這樣:C#打印邊框二維數組

####### 
#  # 
#  # 
#  # 
#  # 
####### 

但是什麼我不不明白的是,我可以在「j == ProcArea.GetUpperBound(...)」部分有一個0或1,並且它可以成功運行而不會出現任何錯誤或意外輸出。

  int[,] ProcArea = new int[rows, columns]; 
      //Generate border 
      for (int i = 0; i < rows; i++) 
      { 
       for (int j = 0; j < columns; j++) 
       { 
        if (i == 0 || j == 0 || i == ProcArea.GetUpperBound(0) || j == ProcArea.GetUpperBound(1)) 
        { 
         ProcArea[i, j] = 2; 

        } 
       } 
      } 

爲什麼這個工作,什麼是我應該使用的正確值?

感謝

回答

2

您在C#中創建的數組(除非直接調用Array.CreateInstance)始終爲0。所以GetUpperBound(0)將始終返回rows - 1,並且GetUpperBound(1)將始終返回columns - 1

因此,代碼將「工作」無論哪個上限您檢查,但我想你會發現,如果rows != columns,然後使用GetUpperBound(0)將創建一個不同大小的盒子比GetUpperBound(1)

順便說一句,讓您的邊境將是一種替代方法:

var maxRow = ProcArea.GetUpperBound(0); 
var maxCol = ProcArea.GetUpperBound(1); 
// do top and bottom 
for (int col = 0; col <= maxCol; ++col) 
{ 
    ProcArea[0, col] = 2; 
    ProcArea[maxRow, col] = 2; 
} 
// do left and right 
for (int row = 0; row <= maxRow; ++row) 
{ 
    ProcArea[row, 0] = 2; 
    ProcArea[row, maxCol] = 2; 
} 

這是稍有更多的代碼,真實的,但你不浪費不必要的時間檢查指標。當然,對小數組不會產生影響。

+0

謝謝,這是一個有趣的做法,我沒有想到。雖然我並不總是製作大小相同的盒子,例如10x11或9x8,那麼這種代碼是否仍然適用? – user9993