【发布时间】:2019-07-26 09:29:39
【问题描述】:
我正在一个 xml 文件中搜索特定元素,我想出了一个好的解决方案,它可以找到我需要的元素,但是,如果我要打开 Option Strict,编译器会告诉我它没有'不允许后期绑定。在 Internet 上进行的快速搜索使我发现绑定需要在执行之前初始化为一种类型,只是不确定如何去做。
我可以简单地关闭该选项,但为了更好的编码,我想保留它,看看如何避免后期绑定。老实说,我什至不知道从哪里开始,我需要一个具有自己属性的类吗?
Dim xmlDocument As String = "C:\***\comp.xml" ' Path '
Dim xelement As XDocument = XDocument.Load(xmlDocument)
Console.WriteLine("What company are you searching for? ")
searchCompData = Console.ReadLine()
Dim results As IEnumerable(Of Object) = From c In xelement.Descendants("COMPANYINFO").Descendants("Office")
Where CType(c.Parent.Parent.Element("compId"), String) = searchCompData
Select New With
{
.reg = c.Parent.Element("Region"),
.city = c.Parent.Element("City"),
.ceo = c.Parent.Element("CEO"),
.office = c
}
For Each res As Object In results
Console.WriteLine(res.reg)
Console.WriteLine(res.city)
Console.WriteLine(res.ceo)
Console.WriteLine(res.office)
Next
Console.ReadLine()
我的示例 xml 文件
<?xml version="1.0" encoding="utf-8"?>
<CompType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyRegion>
<compId>1</compId>
<compRegionId>654</compRegionId>
<compTransPort>Van</compTransPort>
<COMPANYINFO>
<compInfoId>545</compInfoId>
<City>London</City>
<Zip>3214</Zip>
<Zone>535</Zone>
<Region>London Region</Region>
<LocalNumber>54687874</LocalNumber>
<CEO>Alice Goldsmith</CEO>
<CompanyStreet>BongoBingo St</CompanyStreet>
<Office>
<Name>IT</Name>
<Place>2nd Floor</Place>
<Manager>
<Name>Steven Smith</Name>
<Address>Robo Street</Address>
<Phonenumber>12345</Phonenumber>
</Manager>
</Office>
<Office>
<Name>Accountants</Name>
<Place>3d Floor</Place>
<Manager>
<Name>Joana Petersen</Name>
<Address>Lamba Street</Address>
<Phonenumber>54321</Phonenumber>
</Manager>
</Office>
</COMPANYINFO>
</CompanyRegion>
<CompanyRegion>
<compId>2</compId>
<compRegionId>785</compRegionId>
<compTransPort>Truck</compTransPort>
<COMPANYINFO>
<compInfoId>321</compInfoId>
<City>Oslo</City>
<Zip>4598</Zip>
<Zone />
<Region>Oslo Region</Region>
<LocalNumber>458754121</LocalNumber>
<CEO>Michael Jonson</CEO>
<CompanyStreet>BingoBango St</CompanyStreet>
<Office>
<Name>Sales</Name>
<Place>4th Floor</Place>
<Manager>
<Name>Rachel Laurensen</Name>
<Address>Albo Street</Address>
<Phonenumber>55555</Phonenumber>
</Manager>
</Office>
<Office>
<Name>Accountants</Name>
<Place>1st Floor</Place>
<Manager>
<Name>Peter Carlsen</Name>
<Address>Lobo Street</Address>
<Phonenumber>455656</Phonenumber>
</Manager>
</Office>
</COMPANYINFO>
</CompanyRegion>
</CompType>
【问题讨论】:
-
具体抱怨哪一部分?
-
如果你使用 Option Infer On 然后把
Dim results As IEnumerable(Of Object) =改成Dim results =和For Each res As Object In results改成For Each res In results开心吗? -
它在抱怨 res.reg 等,说它不允许后期绑定,如果我要删除 .reg 就可以了。
-
实际上,您的回答有所帮助,通过打开选项推断并将结果作为 ienumerable(of objects) 更改为 Dim results = ,谢谢!