1

我目前一直在使用以下代码将大型 Xml 文件加载到 XTable 中:

Private Sub Button5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
  TextBox4.Visible = False
  Dim asm = Assembly.GetExecutingAssembly()
  Dim var = asm.GetManifestResourceStream("WindowsApplication2.british-english-dictionary.xml")

  Dim rand = New Random()
  Dim myXml = XDocument.Load(var)
  var.Close()

  Dim lexemeList = myXml.Descendants("lexeme").ToList()
  Dim randomLexeme = lexemeList(rand.Next(0, lexemeList.Count - 1))

  TextBox2.Text = randomLexeme.Descendants("grapheme").Value
End Sub

但是,由于 xml 很长(400,000 个条目),因此按下按钮会有些延迟。为了尝试将其最小化,我想Dim myXml = XDocument.Load(var)在按下按钮的外部进行操作,以便仅在打开程序时才将 Xml 文件加载到 XDocument 中,而不是每次按下按钮时。

我试过这样做:

Imports System.IO
Imports System
Imports System.Reflection
Imports System.Xml
Imports System.Security.Permissions

Public Class Form1    
  Public asm = Assembly.GetExecutingAssembly()
  Public var = asm.GetManifestResourceStream("WindowsApplication2.british-english-dictionary.xml")

  Public rand = New Random()
  Public myXml = XDocument.Load(var)

  Private Sub Button5_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
    TextBox4.Visible = False

    Dim lexemeList = myXml.Descendants("lexeme").ToList()
    Dim randomLexeme = lexemeList(rand.Next(0, lexemeList.Count - 1))

    TextBox2.Text = randomLexeme.Descendants("grapheme").Value
  End Sub
End Class

但是当按钮点击事件发生时我收到一个错误:

未找到类型“d__a”的公共成员“ToList”。

4

1 回答 1

4

您不应该在变量初始化器中做任何繁重的工作。相反,使用Sub Newor Form_Load。始终明确指定类型并给变量一个有意义的名称。避免不必要的变量暴露,例如asm可以在Sub New. 例如:

Public var As Stream
Public rand As Random
Public myXml As XDocument

Sub New()
  ' This call is required by the designer.
  InitializeComponent()

  ' Add any initialization after the InitializeComponent() call.
  Dim asm As Assembly = Assembly.GetExecutingAssembly()
  var = asm.GetManifestResourceStream("WindowsApplication2.british-english-dictionary.xml")
  rand = New Random()
  myXml = XDocument.Load(var)
End Sub

从那开始,看看错误是否仍然存在。

附带说明一下,如果将资源文件 (*.resx) 添加到项目中,然后将 XML 资源添加到其中,则可以使代码更简单。然后它变得像调用一样简单:

myXml = XDocument.Load(My.Resources.ResxName.british-english-dictionary.xml)

注意资源名称在编译时检查,VS 为你做管道。

于 2013-02-16T13:43:19.470 回答