【问题标题】:why use of unassigned local variable. C#. create a new node [closed]为什么使用未分配的局部变量。 C#。创建一个新节点[关闭]
【发布时间】:2017-04-11 17:15:43
【问题描述】:

我对以下代码有疑问。如果它与之前创建的不同,我只需要创建一个新的 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);
                }
            }

【问题讨论】:

  • serialPCB 和 node 分配在哪里?显然,您需要向我们展示所有相关代码。
  • “如果该变量不变,我需要使用相同的变量。”哪个变量?目前还不清楚您要在这里实现什么。
  • 在声明为局部变量时赋值nullPCBA pcb = null;
  • 你不能只分配PCBA pcb = serialPCB; 那么如果你的if语句是真的,它只会创建一个新的
  • 抱歉,代码不完整。

标签: c# unassigned-variable


【解决方案1】:

对于每个if,都有一个else。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多