【问题标题】:How to return a jagged array如何返回一个锯齿状数组
【发布时间】:2011-09-15 12:07:33
【问题描述】:

我有一个函数,它使用 2D 锯齿状数组来保存 SQL 查询中的记录。

如何正确返回锯齿状数组?

我尝试了类似的方法:

public string[][] GetResult()
{
    return result;
}

在我的主程序中:

string[][] test = new string[server1.GetResult().Length][];
test = server1.GetResult();

好吧,正如预期的那样,它没有用。

我不知道如何解决我的问题。

【问题讨论】:

  • 前提是正确的,所以还有别的问题——string[][] 不是问题所在。请问有错误信息吗?
  • 仅供参考,分配给test 在声明中毫无意义,因为它被Gronforum.GetResult 的调用覆盖。你到底有什么问题?
  • 我会将函数中锯齿状数组的内容返回给我的主程序。但是我的主程序中的数组是空的。

标签: c# return jagged-arrays


【解决方案1】:

锯齿状数组只是数组的数组。

在您的代码中:

string[][] test = new string[server1.GetResult().Length][];
test = Gronforum.GetResult();

您首先将一个新数组分配给test,然后用GetResult() 的返回值覆盖它。代码与以下内容相同:

string[][] test = Gronforum.GetResult();

现在GetResult() 应该返回一个string[][] - 试试这个来感受一下使用锯齿状数组:

public string[][] GetResult()
{
    string[][] result = new string[2][];
    result[0] = new string[] { "1", "2" };
    result[1] = new string[2];
    result[1][0] = "a";
    result[1][1] = "b";
    return result;
}

您可以向该方法提供对 SQL 操作结果的引用,以便它可以访问数据,将其“转换”为string[][]

【讨论】:

  • 谢谢!我犯了同样的错误两次!我在洞的时候覆盖了数组......它真的是空的。 Wit string[][] test = server1.GetResult();它完美地工作。我用 result[1][1] = "b"; 对其进行了测试,她的函数正确地返回了值。谢谢,伙计们!
猜你喜欢
  • 2014-02-04
  • 2021-11-07
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-23
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
相关资源
最近更新 更多