2016-08-29 112 views
0

我有傳遞參數給類的問題。我想通過每一次迭代來填充數組。將參數傳遞給Class方法

private string[,] links; 

      for (int i = 0; i < 40; i++) 
      { 
       links = sql.Link(i); 
      } 

這就是另一個類中的方法:

public string[,] Link(int i) 
{ 
    SqlCommand sqlCommand = new SqlCommand(); 
    string[,] array = new string[40,40]; 
    int num = 0; 
    sqlCommand.Connection = this.conn; 
    sqlCommand.CommandText = "SELECT TOP (40) Link FROM dbo.Links"; 
    SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); 
    while (sqlDataReader.Read()) 
    { 
     array[i,num] = sqlDataReader.GetValue(0).ToString();       
     num++; 
    } 
    sqlDataReader.Close(); 
    return array; 
} 

的事情是,該Links陣列只包含空值。

當我改變傳遞代碼:

links = sql.Link(0); 

然後從0,00,39各項指標是否正確填寫。但爲什麼傳球不能正常工作?

+0

你確定,檢查I <40循環後的鏈接[39,0] .. [39,39]。你想做什麼,爲什麼要執行相同的SQL 40次? – Serg

回答

0

因爲,在下面的行

string[,] array = new string[40,40]; 要生成一個新的數組和返回相同。

因此,在for循環的第一次迭代期間,在links = sql.Link(i);鏈接數組將包含鏈接[0,0]到鏈接[0,39]的值,但在下一次迭代中,返回新數組對象時,鏈接將現在指向這個新的對象(它將保存[1,0]到[1,39]的值)。

在您當前的情況下,在完成for lop之後,您的links數組變量將包含[39,0]至[39,39]的值,但不包含其他值。

可能的方法

的解決方案是讓一個數組,與前一個合併。 兩種方法顯示如下參考:

1)返回數組的索引在一次迭代中,然後用合併的先前數據

private string[,] links = links[40, 40]; 

for(int i = 0; i < 40; i++) 
{ 
    string[] linksPart = Link(i); 

    for(int j = 0; j < 40; j++) 
    { 
     links[i, j] = linksPart[j]; 
    } 
    // here, your links array variable contain values from [0, 0] through [40, 40] 

    //...rest of the code. 
} 

string[] Link(int i) 
{ 
    string[] linkParts = new string[40]; 

    //connection open and populate array code goes here 
} 

2)傳遞數組作爲參數傳遞給鏈接功能

private string[,] links = links[40, 40]; 

for(int i = 0; i < 40; i++) 
{ 
    Link(i, links); 

    // here, your links array variable contain values from [0, 0] through [40, 40] 

    //...rest of the code. 
} 

string[] Link(int i, string[,] arr) 
{ 
    // no need to create a new array 

    //connection open and other code (before sqlDataReader.Read() line) 
    while (sqlDataReader.Read()) 
    { 
     arr[i , num] = sqlDataReader.GetValue(0).ToString(); 
     num++; 
    } 

    //rest of the code and return statement 
}