C# 无法隐式转换类型`string';至'System.Collections.Generic.List<;int>';

C# 无法隐式转换类型`string';至'System.Collections.Generic.List<;int>';,c#,C#,这应该比较每个列表上的三个数字,如果a中的数字大于B中的数字,则给C一分,如果B中的数字大于a中的数字,则给D一分,如果它们相等,则不起作用。以下是一个例子: Input | output A= 1 3 2 | C D B= 3 2 2 | 1 1 static List<int> compareTriplets(List<int> a, List<int> b) { int c = 0; int d = 0; f

这应该比较每个列表上的三个数字,如果a中的数字大于B中的数字,则给C一分,如果B中的数字大于a中的数字,则给D一分,如果它们相等,则不起作用。以下是一个例子:

Input     | output
A= 1 3 2  |  C D
B= 3 2 2  |  1 1
static List<int> compareTriplets(List<int> a, List<int> b) 
{
    int c = 0;
    int d = 0;

    for (int i=0;i<3;i++)
        if (a[i]>b[i])
            c++;
        else if (b[i]>a[i])
            d++;

    return new List<int>{ c, d };
 }
代码如下:

静态列表compareTriplets(列表a、列表b)
{
int c=0;
int d=0;
对于(int i=0;i<3;i++)
{
如果(a[i]>b[i])
{
C++;
}
else如果(b[i]>a[i])
{
d++;
}
}
返回c+“”+d;
}
此代码返回给我以下信息:

错误CS0029:无法将类型“string”隐式转换为“System.Collections.Generic.List”


您正在尝试将字符串转换为列表。函数
compareTriplets
必须返回字符串

建议:当使用索引进行迭代时,需要检查列表的边界

static string compareTriplets(List<int> a, List<int> b)
{
    int c = 0;
    int d = 0;
    for (int i = 0; i < 3; i++)
    {
        if (a[i] > b[i])
            c++;
        else if (b[i] > a[i])
            d++;
    }
    return c + " " + d;
}

您正在指定函数将返回整数列表:
静态列表
。您需要将此更改为字符串

static String compareTriplets(List<int> a, List<int> b) {
    int c = 0;
    int d = 0;
    for (int i=0;i<3;i++){
        if (a[i]>b[i]){
           c++;
        }
        else if (b[i]>a[i])
        {
            d++;
        }
    }
    return c.ToString() + " " + d.ToString();
 }

您的返回类型是
string
a+“”+b
,因此您需要更改方法签名:

静态字符串比较程序(列表a、列表b){
//等等。。。。

您应该返回type
列表
,但您返回的是
c+“”+d
。我不理解问题的其余部分

您应该返回一个列表。以下是一个示例:

Input     | output
A= 1 3 2  |  C D
B= 3 2 2  |  1 1
static List<int> compareTriplets(List<int> a, List<int> b) 
{
    int c = 0;
    int d = 0;

    for (int i=0;i<3;i++)
        if (a[i]>b[i])
            c++;
        else if (b[i]>a[i])
            d++;

    return new List<int>{ c, d };
 }
静态列表compareTriplets(列表a、列表b)
{
int c=0;
int d=0;
对于(int i=0;ib[i])
C++;
else如果(b[i]>a[i])
d++;
返回新列表{c,d};
}

对我来说,这段代码看起来像是要返回2个数字:

但是,这样它将变成一个字符串,与方法签名不匹配

要返回数字列表(例如2个数字),您可以使用

return new List<int>{c, d};
返回新列表{c,d};

您应该返回
列表
但您返回的是
c++d
。我不理解问题的其余部分。请尝试返回c[I]。ToString()++d[I].ToString;@JuniorCortenbach:那不行。它仍然是一个字符串。可能返回签名应该是
string
?花点时间想想你在做什么。函数应该返回什么?它应该返回一个字符串吗?还是应该返回一个包含两个值的列表?你在
return
。字符串被隐式转换@JoshuaSchlichting@JoshuaSchlichting:它将编译并运行。很有趣。我认为在那里进行强制转换是合适的。您不需要调用
ToString
,它会自动为您执行此操作。这适用于每个
对象,而不仅仅是
int
。我的错误!我更喜欢by显式,但我没有意识到int没有.toString()!它有一个
toString()
,上面有一个t。
return new List<int>{c, d};