2013-03-16 90 views
1

我正在從一本書學習c#,並且必須自行編寫代碼作爲練習的一部分。其中一件事是將double數組傳遞給構造函數重載方法之一,後者將進一步處理它。問題是我不知道該怎麼做。C#將雙數組傳遞給構造函數重載方法

這裏談到的完整代碼(至今):代碼

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace assignment01v01 
{ 

    public class Matrix 
    { 
     int row_matrix; //number of rows for matrix 
     int column_matrix; //number of colums for matrix 
     int[,] matrix; 

     public Matrix() //set matrix size to 0*0 
     { 
      matrix = new int[0, 0]; 
      Console.WriteLine("Contructor which sets matrix size to 0*0 executed.\n"); 
     } 

     public Matrix(int quadratic_size) //create quadratic matrix according to parameters passed to this constructor 
     { 
      row_matrix = column_matrix = quadratic_size; 
      matrix = new int[row_matrix, column_matrix]; 
      Console.WriteLine("Contructor which sets matrix size to quadratic size {0}*{1} executed.\n", row_matrix, column_matrix); 
     } 

     public Matrix(int row, int column) //create n*m matrix according to parameters passed to this constructor 
     { 
      row_matrix = row; 
      column_matrix = column; 
      matrix = new int[row_matrix, column_matrix]; 
      Console.WriteLine("Contructor which sets matrix size {0}*{1} executed.\n", row_matrix, column_matrix); 
     } 

     public Matrix(int [,] double_array) //create n*m matrix and fill it with data passed to this constructor 
     { 
      matrix = double_array; 
      row_matrix = matrix.GetLength(0); 
      column_matrix = matrix.GetLength(1); 
     } 

     public int countRows() 
     { 
      return row_matrix; 
     } 

     public int countColumns() 
     { 
      return column_matrix; 
     } 

     public float readElement(int row, int colummn) 
     { 
      return matrix[row, colummn]; 
     } 
    } 


    class Program 
    { 
     static void Main(string[] args) 
     { 
      Matrix mat01 = new Matrix(); 

      Matrix mat02 = new Matrix(3); 

      Matrix mat03 = new Matrix(2,3); 

      //Here comes the problem, how should I do this? 
      Matrix mat04 = new Matrix ([2,3] {{ 1, 2 }, { 3, 4 }, { 5, 6 }});   

      //int [,] test = new int [2,3] { { 1, 2, 3 }, { 4, 5, 6 } }; 

     } 
    } 
} 

部分困擾我的是標有「//這裏說到這個問題,我應該怎麼辦呢?」。

歡迎任何建議。

回答

2

可以按如下方式創建多維數組。

new Matrix(new int[,] {{1, 2, 3,}, {1, 2, 3}}); 

int甚至是多餘的,因此您可以使其更容易(或者,至少,它應該是更容易閱讀:))

new Matrix(new [,] {{1, 2, 3,}, {1, 2, 3}}); 
+0

該死「你是人類」對話讓我忙.... Jared說什麼...... :) PS:是的!我是人! – bas 2013-03-16 16:22:59

+0

您的解決方案就像一個魅力,謝謝。 – 2013-03-16 16:39:19

3

看起來你正在努力如何用一組初始值創建一個多維數組。其語法如下

new [,] {{ 1, 2 }, { 3, 4 }, { 5, 6 }} 

因爲在這種情況下您正在初始化數組,所以不需要指定大小或類型。編譯器會根據提供的元素推斷出它。

1

您只要有指數切換,並缺少new關鍵字。這應該工作:

Matrix mat04 = new Matrix (new [3,2] {{ 1, 2 }, { 3, 4 }, { 5, 6 }}); 

或者,如@JaredPar指出,就可以完全省略數組的大小,並讓編譯器推斷它爲您:

Matrix mat04 = new Matrix (new [,] {{ 1, 2 }, { 3, 4 }, { 5, 6 }}); 
+0

是的,我選擇瞭解決方案: Matrix mat04 = new Matrix(new [,] {{1,2},{3,4},{5,6}}); – 2013-03-16 16:40:20