【问题标题】:Passing argument to Class method将参数传递给 Class 方法
【发布时间】:2017-01-05 12:46:23
【问题描述】:

我在将参数传递给类时遇到问题。我想通过将填充数组的每个迭代。

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 的每个索引都被正确填充。但是为什么传不正常呢?

【问题讨论】:

  • 你确定吗,在 I

标签: c# sql arguments


【解决方案1】:

因为,在下面一行

string[,] array = new string[40,40]; 您正在生成一个新数组并返回相同的数组。

所以在 for 循环的第一次迭代中,links = sql.Link(i); links 数组将包含 links[0, 0] 到 links[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) 将数组作为参数传递给 Link 函数

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
}

【讨论】:

    猜你喜欢
    • 2014-12-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2011-07-23
    • 2013-10-04
    • 2013-05-19
    • 2013-02-08
    • 2021-07-19
    相关资源
    最近更新 更多