错误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]);
    }

    // ...
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...