【问题标题】:Error CS0029: Cannot implicitly convert type 'string' to 'int'错误 CS0029:无法将类型“字符串”隐式转换为“整数”
【发布时间】:2021-02-14 07:03:05
【问题描述】:

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

错误 CS0029:无法将类型“字符串”隐式转换为“整数”

我做错了什么?

代码:

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

    // ...
}

【问题讨论】:

  • 想一想:您正在尝试将字符串形式的人名存储到整数数组中。
  • 更改自:int[] people = new int[size]; To : string[] people = new string[size];

标签: c# windows-console


【解决方案1】:

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

String[] people = new String[size];

或

var people = new String[size];

【讨论】:

    【解决方案2】:

    你应该定义string[] 而不是int[] 所以使用字符串[]

    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]);
        }
    
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2015-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多