【问题标题】:Display an array from a method using another method?使用另一种方法显示方法中的数组?
【发布时间】:2016-05-31 01:16:39
【问题描述】:

我基本上想在我的主要方法上显示一个方法中的一个数组。 第一种方法是带有数组的方法,第二种方法是我想用来显示它的方法,但我不知道如何。

对不起,如果这很明显,我就是想不通

static public string[] MakeInsults(string[] sNames, string[] sVerbs, string[] sObjects, out int iNumber)
{
    Random random = new Random();
    Utility.GetValue(out iNumber, "Enter the number of insults to generate: ", 5, 100);
    string[] Insults = new string[iNumber];

    for (int i = 0; i < Insults.Length; i++)
    {
        Insults[i] = sNames[random.Next(0, 4)] + " " + sVerbs[random.Next(0, 4)] + " " + sObjects[random.Next(0, 4)];
    }

    return Insults;
}
static public string DisplayInsults(string[] sInsults)
{
   //Use this to display MakeInsults()
}

【问题讨论】:

  • 只是控制台将内容写入数组?

标签: c# arrays methods


【解决方案1】:

你可以通过两种方式做到这一点:

  • DisplayInsults() 致电MakeInsults():为此,您需要在DisplayInsults 中进行以下更改;

DisplayInsults 的返回类型更改为 void,然后无参数 是需要的。方法如下:

static public void DisplayInsults()
{
    Console.WriteLine("The elements in the array are:\n");
    Console.WriteLine(String.Join("\n",MakeInsults(sNames,sVerbs,sObjects,iNumber));
}
  • MakeInsults() 致电DisplayInsults():为此,您需要在MakeInsults 中进行以下更改;

MakeInsults 的返回类型更改为 void,然后调用 DisplayInsults 代替返回。方法如下:

static public void MakeInsults(string[] sNames, string[] sVerbs, string[] sObjects, out int iNumber)
{
    //Process your statements;
    DisplayInsults(Insults);
}

DisplayInsults 的定义如下:

static public void DisplayInsults(string[] sInsults)
{
    Console.WriteLine("The elements in the array are:\n");
    Console.WriteLine(String.Join("\n",sInsults);
}

【讨论】:

    【解决方案2】:

    如果是控制台应用:

    public static void DisplayInsults(string[] sInsults)
     {
       for (int i = 0; i < sInsults.Length; i++) {
         System.Console.Out.WriteLine(sInsults[i]);
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-18
      • 2017-10-30
      • 2015-06-15
      • 2021-11-18
      • 1970-01-01
      • 2017-04-26
      • 2015-05-10
      • 2013-02-10
      相关资源
      最近更新 更多