0
static string[] myFriends = new string[] {"Robert","Andrew","Leona","Ashley"};

如何从这个静态字符串数组中提取名称,以便可以在不同的行上单独使用它们?如:

罗伯特坐在 1 号椅子上

安德鲁坐在椅子上 2

Leona 坐在 3 号椅子上

Ashley 坐在 4 号椅子上

我猜我必须将它们分配给值,然后在 a 中WriteLine Command,我会为每个相应的名称输入 {1}、{2}、{3} 等?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Friends
{
class Program
{
    public void count(int inVal)
    {
        if (inVal == 0)
            return;
        count(inVal - 1);

        Console.WriteLine("is sitting in chair {0}", inVal);
    }

    static void Main()
    {
        Program pr = new Program();
        pr.count(4);
    }

    static string[] myStudents = new string[] {"Robert","Andrew","Leona","Ashley"};

}
}

我想将名称添加到“坐在椅子上”行。

4

2 回答 2

1

我认为 @TGH 提到的fororforeach是要走的路。虽然这听起来像是教科书练习,而不是递归的工业用途,但它不是一个很好的递归使用。

如果你想按原样修复你的,使用递归,将方法更改为:

public void count(int inVal)
{
    if (inVal == 0)
        return;
    count(inVal - 1);

    // arrays are 0-based, so the person in chair 1 is at array element 0
    Console.WriteLine("{0} is sitting in chair {1}", myStudents[inVal-1], inVal);
}
于 2013-10-11T03:01:52.333 回答
0

使用 Linq 扩展将代码简化为:

int chairNo =1;
myFriends.ToList().ForEach(x =>  Consol.WriteLine(string.Format("{0} is sitting in chair {1}", x, chairNo++)));

记得把关注放在首位;使用 System.Linq;

于 2013-10-11T05:53:47.823 回答