为什么使用未分配的局部变量。 C#。创建一个新节点

时间:2017-04-11 17:15:44

标签: c# unassigned-variable

我遇到以下代码问题。我需要创建一个新的pcba节点,如果它与之前创建的不同。如果该变量没有改变,我需要使用相同的变量。

foreach (XmlNode node in dc.DocumentElement.ChildNodes)
            {
                PCBA pcb = null;

                if (serialPCB != node.Attributes["PCBpos"].Value.ToString())
                    pcb = new PCBA();

                pcb.PCBA_Status = status;
                long number = 0;
                bool validation = false;
                if (node.Attributes != null && node.Attributes["PCBpos"] != null)
                  {
                    validation = long.TryParse(node.Attributes["PCBpos"].Value, out number);
                  }
                 //bool validation = long.TryParse(node.Attributes["PCBpos"].Value, out number);
                if (validation == true)
                {
                    pcb.PCBA_POSITION = node.Attributes["PCBpos"].Value.ToString();
                    serialPCB = node.Attributes["PCBpos"].Value.ToString();

                    if (status != "PASS")
                    {
                        List<Group> groups = new List<Group>();
                        Group group = new Group();

                        group.Group_Name = node.Attributes["COMP_NAME"].Value.ToString();
                        group.Group_Status = status;
                        group.Group_FailureCode = node.Attributes["FaultName"].Value.ToString();

                        List<Measurement> measurements = new List<Measurement>();
                        Measurement measurement = new Measurement();
                        measurement.Measurement_Name = node.Attributes["COMP_NAME"].Value.ToString();
                        measurement.Measurement_Status = status;
                        DirectoryInfo di = new DirectoryInfo(dc.DocumentElement.Attributes["LOCATION"].Value.ToString());
                        var ruta = di.GetFiles(node.Attributes["COMP_NUMBER"].Value.ToString() + "-*");
                        if (ruta.Length > 0)
                            measurement.Measurement_ImagePath = di + "\\" + ruta[0].ToString();
                        measurements.Add(measurement);
                        group.Measurements = measurements;
                        groups.Add(group);
                        pcb.Groups = groups;
                    }

                    pcbas.Add(pcb);
                }
            }

1 个答案:

答案 0 :(得分:5)

对于每个if,都有一个else

在您的情况下,如果条件为false,则不会分配pcb

首先将其设置为null。然后在再次使用之前检查它是否仍为空。