我试图从保存的自定义文件中读取值,但它始终只读取列表中的第一个字符串。
例如,我在列表中保存了两个单词(“ FIRST”,“ SECOND”),使用下面的代码将成功保存两个单词,但是当反序列化文件以读取文件时,它仅使用第一个单词“ FIRST”覆盖它”。
读取方法:
public static List<string> GetBonusList()
{
if (File.Exists(GetCurrentGamePath()))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream existingFile = File.Open(GetCurrentGamePath(), FileMode.Open);
gameList = (List<Game>)formatter.Deserialize(existingFile);
existingFile.Close();
foreach (Game game in gameList.Where(x => x.GameName == gameName))
{
if (game.FoundBonusWordsList != null)
return game.FoundBonusWordsList;
else
return null;
}
Debug.Log("No bonus words found yet!");
return null;
}
else
{
Debug.Log("File doesn't exists yet.");
return null;
}
}
保存方法:
public static void SaveBonusWord(string bonusWord)
{
BinaryFormatter formatter = new BinaryFormatter();
/// Check if there is a file
/// containing revealed word OR bonus words OR both.
if (File.Exists(GetCurrentGamePath()))
{
FileStream existingFile = File.Open(GetCurrentGamePath(), FileMode.Open);
gameList = (List<Game>)formatter.Deserialize(existingFile);
foreach (var existingGame in gameList.Where(x => x.GameName == gameName))
if (existingGame.FoundBonusWordsList.Contains(bonusWord) == false)
existingGame.FoundBonusWordsList.Add(bonusWord);
formatter.Serialize(existingFile, gameList);
existingFile.Close();
}
else
{
Debug.Log("No boardWord or bonusWord found yet. Creating new game..");
FileStream file = File.Create(GetCurrentGamePath());
Game game = new Game
{
GameName = gameName
};
game.FoundBonusWordsList.Add(bonusWord);
gameList.Add(game);
formatter.Serialize(file, gameList);
file.Close();
}
}