【问题标题】:Adding values to an array, returns "System.Int32[]"向数组添加值,返回“System.Int32[]”
【发布时间】:2015-11-09 17:43:38
【问题描述】:

我正在尝试向数组添加值,然后在 10 次增量后返回整个数组。

public int[] multi(int x)
{
    int[] array = new int[10];
    for (int i = 1; i < array.Length; i++)
    {
        array[i] = x;
        x += x;
    }
    return array;
}

但是,当我调用该方法时,它只返回 System.Int32[],而不是(在这种情况下)5、10、15、20 等。

int[] result = lab.multi(5);
Console.WriteLine(result);

感谢所有帮助!

【问题讨论】:

  • 这是设计使然。在Object 中定义的.ToString() 的默认实现(.NET 中的所有内容都从该实现派生)返回类型——在本例中为System.Int32[](即Int32 的数组)。 Console.WriteLine() 在对象上调用 ToString()。您需要遍历数组以打印出元素值。

标签: c# arrays return add


【解决方案1】:

函数Console.WriteLine 在对象上调用ToString(),因此对于引用类型,它只打印类型名称,在您的情况下为System.Int32[]

如果要打印整数数组,可以使用函数string.Join:

int[] result = lab.multi(5);
Console.WriteLine(string.Join(", ", result));

【讨论】:

    【解决方案2】:

    Console.WriteLine 没有int[] 的重载,因此它使用调用ToString() 方法的object 重载。 ToString on int[] 打印出 System.Int32[]

    您需要遍历并打印出每个项目。

    foreach(var item in result)
    {
        Console.WriteLine(item);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-06
      • 2014-04-21
      • 2017-03-14
      • 2010-09-17
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多