不能将类型 float 隐式转换为 float[]

Error    CS0029  Cannot implicitly convert type 'float' to 'float[]'尝试编译此代码时出错


        float[] timeValues;


        float time;


        while (lineBeingRead != null)

        {

            valueSplit = lineBeingRead.Split(exerciseDivider);

            for (int i = 0; i < valueSplit.Length; i++)

            {

                if (valueSplit[i].Contains(textToFind))

                {

                    exerciseLine = valueSplit[i];


                    string[] timeValuesString = exerciseLine.Split(timeDivider);


                    for (int a = 0; a < timeValuesString.Length; i++)

                    {

                        time = float.Parse(timeValuesString[1]);

                        timeValues = time;

                    }

                }

            }

        }

有谁知道这里发生了什么?我无法弄清楚这一点,也找不到任何答案。


守着星空守着你
浏览 710回答 2
2回答

LEATH

您需要在使用之前实例化您的数组,并且您不能将单个浮点分配给整个数组。更改代码的以下部分string[] timeValuesString = exerciseLine.Split(timeDivider);timeValues = new float[timeValuesString.Length]; // CHANGE-1for (int a = 0; a < timeValuesString.Length; i++){&nbsp; &nbsp; time = float.Parse(timeValuesString[1]);&nbsp; &nbsp; timeValues[a] = time; // CHANGE-2}

天涯尽头无女友

您正在尝试为数组分配一个浮点数(而不是将其添加为数组的元素)。因此,您必须首先使用预定义的大小初始化数组:timeValues = new float[neededLength]。但是如果你不知道你需要的尺寸,List<float>类型是更好的选择,如下代码://float[] timeValues;List<float> timeValues = new List<float>();float time;while (lineBeingRead != null){&nbsp; &nbsp; valueSplit = lineBeingRead.Split(exerciseDivider);&nbsp; &nbsp; for (int i = 0; i < valueSplit.Length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (valueSplit[i].Contains(textToFind))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exerciseLine = valueSplit[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string[] timeValuesString = exerciseLine.Split(timeDivider);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int a = 0; a < timeValuesString.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time = float.Parse(timeValuesString[1]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //timeValues = time;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; timeValues.add(time);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}您也可以在需要时通过调用它的ToArray方法将列表转换为数组:var timeArray = timeValues.ToArray();
打开App,查看更多内容
随时随地看视频慕课网APP