質問

where is the error here . In the bottom of the code .

Error 1 Use of unassigned local variable 'Interfaces'

public static void Create_Interfaces()
{
      XDocument Interfaces;
    List<string> intf = new List<string>{"em0","em1","em2"};

    foreach (var i in intf)
    {
        Interfaces = new XDocument(
      new XElement("Interfaces",
        new XElement("Interface",
          new XElement("name", i),
          new XElement("vlan-tagging", XElement.EmptySequence),
          new XElement("unit",
          new XElement("vlan-id", "10"),
          new XElement("family", new XElement("inet", new XElement("address", new XElement("name", "10.10.1.23/24"))))))));
    }
    Interfaces.Save("Interfaces.xml");

}
役に立ちましたか?

解決

The C# compiler is not as smart as you are. Even though you know that there will always be something to loop through, the compiler does not.

Because of this, the compiler thinks there is a chance that intf is empty in which case Interfaces will never be assigned. Since you are trying to call Save(..); on Interfaces after the loop, the compiler complains.

That being said, it seems like you are reassigning Interfaces in every loop, without using the result from the previous iterations(thereby throwing away the previous iterations XDocuments). Is this intentional?

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top