错误CS0029:无法将类型'string'隐式转换为'int'

问题描述

在我的程序中,我必须使用7个名称并按字母顺序显示它们。但是我得到了错误

错误CS0029:无法将类型'string'隐式转换为'int'

我在做什么错了?

代码

static void Main(string[] args)
{
    int size = 7;
    
    int[] people = new int[size];
    
    for(int i = 0; i < size; i++)
    {
        Console.WriteLine("Please enter " + i+1 + ". person's name: ");
    
        // Here
        people[i] = Console.ReadLine();
    }
    
    Console.WriteLine("After alphabetic ordering: ");
    
    Array.sort(people);
    
    for (int j = 0; j < size; j++)
    {
        Console.WriteLine(j + 1 + "person's name : " + people[j]);
    }

    // ...
}

解决方法

ReadLine方法返回一个字符串。因此,此代码尝试将字符串值分配给int变量people。 像下面这样重写代码。

String[] people = new String[size];

var people = new String[size];
,

您应该定义string[]而不是int[],因此请使用string []

static void Main(string[] args)
{
    int size = 7;
    
    string[] people = new string[size];
    
    for(int i = 0; i < size; i++)
    {
        Console.WriteLine("Please enter " + i+1 + ". person's name: ");
        
        // Here
        people[i] = Console.ReadLine();
    }
    
    Console.WriteLine("After alphabetic ordering: ");
    
    
    
    Array.Sort(people);
    
    for (int j = 0; j < size; j++)
    {
        Console.WriteLine(j + 1 + "person's name : " + people[j]);
    }

    // ...
}