无法将int隐式转换为int []

时间:2016-02-16 15:03:23

标签: c# casting console-application

有一些解决方案,但没有一个对我有用。至于我的问题,我正在构建多个数组。以下是我的变量和我遇到问题的代码:

static int      numOfEmployees;
static string[] nameArray;
static int[]    idArray, deptArray;
static double[] payArray, hoursArray;

static void InputEmployeeData()
{
    int      i;
    string[] words;

    numOfEmployees  = Int32.Parse(fileIn.ReadLine());
    idArray         = new int[numOfEmployees + 1];
    nameArray       = new string[numOfEmployees + 1];
    deptArray       = new int[numOfEmployees + 1];
    payArray        = new double[numOfEmployees + 1];
    hoursArray      = new double[numOfEmployees + 1];

    for (i = 1; i <= numOfEmployees; i++)
    { 
        words       = fileIn.ReadFields();
        idArray     = Int32.Parse(words[0]);
        nameArray   = words[1];
        deptArray   = Int32.Parse(words[2]);
        payArray    = Double.Parse(words[3]);
        hoursArray  = Double.Parse(words[4]);
    }
}

在我的for循环中,我得到的每一行都是&#34;不能隐式地将int类型转换为int []。或者输入double to double []。

我尝试过铸造似乎失败了。

2 个答案:

答案 0 :(得分:6)

这是因为您正在尝试分配数组而不是分配其成员:

idArray     = Int32.Parse(words[0]);

应该是

idArray[i]  = Int32.Parse(words[0]);

等等。更好的是,创建EmployeeData类,其中包含idnamedept等各个字段,并使用它代替并行数组:

class EmployeeData {
    public int Id {get;}
    public string Name {get;}
    public int Dept {get;}
    public double Pay {get;}
    public double Hours {get;}
    public EmployeeData(int id, string name, int dept, double pay, double hours) {
        Id = id;
        Name = name;
        Dept = dept;
        Pay = pay;
        Hours = hours;
    }
}

现在您可以创建一个数组或EmployeeData列表,并在阅读其信息时创建个别员工:

var employee = new EmployeeData[numOfEmployees];
// Index i starts from 0, not from 1
for (i = 0; i < numOfEmployees; i++) { 
    words       = fileIn.ReadFields();
    var id = Int32.Parse(words[0]);
    var name = words[1];
    var dept = Int32.Parse(words[2]);
    var pay = Double.Parse(words[3]);
    var hours = Double.Parse(words[4]);
    employee[i] = new EmployeeData(id, name, dept, pay, hours);
}

答案 1 :(得分:0)

您正在尝试将int值分配给int数组。这会导致类型不匹配,从而导致编译器错误。

您真正想要做的是索引数组并在指定的索引处分配int。

idArray[i] = int.Parse(words[0]);