我正在學習大學的VB,並且遇到了一個與我的任務中的一個障礙。有人可以幫忙嗎?我的目標嘗試採取以下字典代碼:將VB字典中的條目寫入文本文件
Public Class Inventory
Public ItemInventory As New Dictionary(Of String, Item)
Public Function iItem(ByVal key As String) As Item
Return ItemInventory(key)
End Function
Public Sub addItem(ByVal item As String, ByVal Desc As String, ByVal DRate As Double, ByVal WRate As Double, _
ByVal MRate As Double, ByVal Quantity As Integer)
With ItemInventory
.Add(item, New Item(item, Desc, DRate, WRate, MRate, Quantity))
End With
End Sub
Public Sub removeItem(ByVal item As String)
With ItemInventory
.Remove(item)
End With
End Sub
Public Function returnKeys() As String()
Dim Keys() As String
With ItemInventory
Keys = .Keys.ToList.ToArray
End With
Return Keys
End Function
End Class
不漂亮,我知道,但它能夠完成任務,這就是我的目標是盡。現在有一點也與在程序中顯示字典項目有關,我也遇到了問題,但是,我想一次只採取這一步,所以我們會在稍後處理, 如果可能的話。
由於每寫,這是我的讀取和寫入電流代碼:
Imports System.IO
Public Class InventoryFile
Public Sub RFile(ByVal FPath As String, ByRef dInventory As Inventory)
Dim infile As StreamReader = File.OpenText(FPath)
Dim entireLine As String = infile.ReadLine()
Dim fields() As String = entireLine.Split(","c)
While infile.EndOfStream
Dim dItem As New Item
dItem.ID = fields(0)
dItem.Description = fields(1)
dItem.Daily = fields(2)
dItem.Weekly = fields(3)
dItem.Monthly = fields(4)
dItem.Quantity = fields(5)
'AddItem
dInventory.addItem(dItem.ID, dItem.Description, dItem.Daily, dItem.Weekly, _
dItem.Monthly, dItem.Quantity)
End While
End Sub
Public Sub WFile(ByVal FPath As String, ByRef dInventory As Inventory)
Dim outfile As StreamWriter = File.CreateText(FPath)
For Each Item As KeyValuePair(Of String, Item) In dInventory.ItemInventory
Next
End Sub
End Class
我希望貼權。現在,就我所瞭解的來說,就文件進入字典而言,閱讀起來很順利,然而我的StreamWriter的「WFile」卻讓我難以理解。有人可以幫助我嗎?同樣,它應該在關閉時關閉並寫入文件,而我關閉按鈕的唯一代碼是Me.Close()命令。我將如何編寫觸發器來使程序寫入文件?知道主表單代碼和我的'庫存文件'都是獨立的類,所以這必須通過引用其他類的問題來完成
一個相當大的調整。 RFile中的while循環不包含Readline。如果你的文件只有一行,你的代碼將會工作。然而,不止一行,沒有任何內容會被添加到字典中,或者最多隻添加到最後一行。使用'While not infile.EndOfStream'並且也包含Readline語句。 – tinstaafl
啊!我知道我忘了那部分!感謝那! – NFSRacer