我有一个名为“游戏”的自定义类。假设我创建了这个类的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
我在sub“findMario()”中放入什么来让“game”的实例名称属性等于“Mario”?
答案 0 :(得分:2)
您可以这样做:
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