1

我有一个名为“游戏”的自定义类。假设我创建了这个类的 3 个实例。

Public Class FrmMain
  Public Sub addGames()
    for x As Integer = 1 To 3 Step 1
      Dim game As New game
      if x = 1 then game.name = "Zelda"
      if x = 2 then game.name = "Mario"
      if x = 3 then game.name = "Donkey Kong"
    next
  End Sub

  Public Sub findMario()
    'What goes here?
  End Sub
End Class

我在我的子“findMario()”中放入什么来获取“游戏”实例的名称属性等于“马里奥”?

4

1 回答 1

3

你可以这样做:

Public Class FrmMain
    Dim games as new List(of game)

    Public Sub addGames()
        games.Add(New Game With {.Name = "Zelda"})
        games.Add(New Game With {.Name = "Mario"})
        games.Add(New Game With {.Name = "Donkey Kong"})
    End Sub

    Public Sub findMario()
        Dim result = (From game In games
                     Where game.Name.Equals("Mario")
                     Select game).FirstOrDefault

        'Do something with the result
    End Sub
End Class

如果您需要从外部文本文件中检索游戏名称,您可以执行以下操作:

Public Sub addGames()
    Dim names = File.ReadAllLines("C:\games.txt")        

    names.ToList().ForEach(Sub(x) games.Add(New Game With {.Name = x}))
End Sub
于 2012-11-30T05:52:11.000 回答