0

我有一个Player用于创建List(Of Player). 我需要在应用程序关闭时保存它。在 Windows 窗体中,我只是序列化,但在 UWP 中不再可能,所以我不得不谷歌了几十个小时,最后我偶然发现了Microsoft.Toolkit.Uwp, then Newtonsoft.Json,但我很遗憾地无法使用它们。我需要你的帮助!

假设我有一个小班:

Dim Name As String
Dim Score As Double
Public Class Player
    <JsonConstructor()>
    Public Sub New(Name As String, Score As Double) ' New with score
        Me.Name = Name
        Me.Score = Math.Max(1, Score)
    End Sub
End Class
Public Overrides Function ToString() As String ' ToString
    Return $"{Name} [{Score}]"
End Function

如何成功读取和写入List(Of Player)?

' Loading MainPage.xaml
Private Sub MainPage_Loading() Handles Me.Loading
    ReadAsync()
    MainFrame.Margin = New Thickness(0)
    Window.Current.Content = MainFrame
    MainFrame.Navigate(GetType(PlayerList), Players)
End Sub

' Read
Private Async Sub ReadAsync()
    Players = JsonConvert.DeserializeObject(Of List(Of Player))(Await FileIO.ReadTextAsync((Await StorageFolder.CreateFileAsync("players.json", CreationCollisionOption.OpenIfExists))))
    If Players Is Nothing Then
        Players = New List(Of Player)
        WriteAsync()
    End If
End Sub

' Write
Public Shared Async Sub WriteAsync()
    Await FileIO.WriteTextAsync(Await StorageFolder.CreateFileAsync("players.json", CreationCollisionOption.ReplaceExisting), JsonConvert.SerializeObject(Players, Formatting.Indented))
End Sub

' Loading PlayerList.xaml
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
    ListBoxPlayers.Items.Clear()
    Players = e.Parameter
    For Each Player In Players
        ListBoxPlayers.Items.Add(Player)
    Next
End Sub

' Adding a new player in the interface
Private Sub ButtonAddPlayer_Click(sender As Button, e As RoutedEventArgs) Handles ButtonAddPlayer.Click
    ' ...
    ' Commit
    MainPage.Players.Add(New Player(TextBoxName.Text))
    ListBoxPlayers.Items.Add(MainPage.Players(MainPage.Players.Count - 1))
    MainPage.WriteAsync()
End Sub

所以这一切都令人困惑。当我通过界面添加播放器时,它会像往常一样进入我的 ListBox。但是,当我关闭应用程序并重新打开它时,我得到了一些空对象。

不同球员名单 序列化无效!

我做了一些愤怒的测试来更多地了解我的问题,结果证明我根本没有序列化,但我可能正确反序列化。

愤怒的测试

4

1 回答 1

1

我找到了,原来是在我的课Player上。

我用了什么:

Dim Name As String
Dim Score As Double

什么有效:

Public Name As String
Public Score As Double

我应该做的:

Public Property Name As String
Public Property Score As Double

我被教导在用 Java 编码时永远不要将变量设置为“公共”,而且我不知道Property在 Visual Basic 中存在这种情况。

于 2017-07-29T04:52:29.733 回答