从方法返回 List<int> 并在 C# 中打印值时出现问题

Jac*_*man 2 c# console-application .net-core-3.0

我有一个像这样的方法,static List<int> Compare(List<int> a, List<int> b) 我希望这个函数return [aPoints bPoints]类似于[2 1] 但是,我坚持在循环后使用if语句存储值并将它们放入分数中。我试过这个:

static List<int> Compare(List<int> a, List<int> b)
{        
    int aPoints = 0;
    int bPoints = 0;
    List<int> score = new List<int>() { aPoints, bPoints }; 

    for (int i = 0; i < 3; i++)
    {
        if (a[i] > b[i])
        {
            aPoints++;
        }
        else if (a[i] < b[i])
        {
            bPoints++;
        }
    }

    return score;
}
Run Code Online (Sandbox Code Playgroud)

并将它们打印在:

static void Main(string[] args){}
Run Code Online (Sandbox Code Playgroud)

Jav*_*tíz 5

这是一个非常简单的解决方案。只需创建一个空列表,并在返回调用者之前将aPoints和添加bPoints到其中。

static List<int> Compare(List<int> a, List<int> b)
{        
    int aPoints = 0;
    int bPoints = 0;
    List<int> score = new List<int>();

    for (int i = 0; i < 3; i++)
    {
        if (a[i] > b[i])
        {
            aPoints++;
        }
        else if (a[i] < b[i])
        {
            bPoints++;
        }
    }
    score.Add(aPoints);
    score.Add(bPoints);
    return score;
Run Code Online (Sandbox Code Playgroud)
  • 或者您可以直接创建列表,如下所示return
static List<int> Compare(List<int> a, List<int> b)
{        
    int aPoints = 0;
    int bPoints = 0;

    for (int i = 0; i < 3; i++)
    {
        if (a[i] > b[i])
        {
            aPoints++;
        }
        else if (a[i] < b[i])
        {
            bPoints++;
        }
    }

    return new List<int>() { aPoints, bPoints};
Run Code Online (Sandbox Code Playgroud)
  • 另外,您可以使用语义上更正确的方法,因为您的列表始终有 2 个值。使用元
static (int aPoints, int bPoints) Compare(List<int> a, List<int> b)
{        
    int aPoints = 0;
    int bPoints = 0;

    for (int i = 0; i < 3; i++)
    {
        if (a[i] > b[i])
        {
            aPoints++;
        }
        else if (a[i] < b[i])
        {
            bPoints++;
        }
    }

    return (aPoints, bPoints);
}
Run Code Online (Sandbox Code Playgroud)

根据您的评论,如果您想打印该Compare方法返回的内容,那么,您可以执行以下操作List<int>

List<int> ret = Compare(someList, anotherList);
foreach (int n in ret)
{
    Console.WriteLine(n);
}
Run Code Online (Sandbox Code Playgroud)
  • 或者你可以使用for像这样的经典循环:
List<int> ret = Compare(someList, anotherList);
for (int i = 0; i < 2; i++)
{
    Console.WriteLine(ret[i]);
}
Run Code Online (Sandbox Code Playgroud)

但是,在此循环中,假设列表中始终包含 2 个元素。一般方法是将循环定义更改为,for (int i = 0; i < ret.Count; i++)以便它像循环一样迭代列表中的每个可用项目foreach