将参数传递给Class方法

时间:2016-08-29 13:03:58

标签: c# sql arguments

将参数传递给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的每个索引都已正确填充。但为什么传球不能正常工作?

1 个答案:

答案 0 :(得分: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
}
相关问题