2016-08-29 113 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 
}