public void Save()
{
Storage = "My String"
}
如您所见,它的使用没有什么特别之处。此属性与任何其他属性之间的区别在于,它的内容在保存游戏时会保存到您的磁盘中。
将其更改为任何旧字符串,这不是很有用,是吗。如果您需要保存更复杂的内容怎么办?好吧,恐怕你将不得不自己做艰苦的工作。
在 Storage 中存储多个值的绝对最简单和原始的方法是使用 string concatenation 或 string.Join 进行保存,使用string.Split 进行加载。
我建议您使用 Program() 来读取您的存储,并使用 Save() 来写入并保留它,以避免经常做太多的工作。
string _someTextDescription;
int _someImportantNumber;
public Program()
{
string[] storedData = Storage.Split(';');
// If there's at least one item in the storage data...
if (storedData.Length >= 1)
{
// Retrieve first item. C# arrays are 0-indexed, meaning the first item in the list is item 0.
_someTextDescription = storedData[0];
}
// If there's at least two items in the storage data...
if (storedData.Length >= 2)
{
// Retrieve the second item. This time we want to try to convert it into a number.
int.TryParse(storedData[1], out _someImportantNumber);
}
}
public void Save()
{
// Combine the state variables into a string separated by the ';' character
Storage = string.Join(";",
_someTextDescription ?? "",
_someImportantNumber
);
}
注意在 Program() 中使用 int.TryParse。我们使用它是因为如果字符串包含我们不理解的内容,我们希望尽最大努力优雅地失败。如果我们更改字符串的格式,或者我们在保存过程中以某种方式出错,就会发生这种情况。安全总比后悔好。
同样,请注意我们添加了 null-coalescing operator运算符 ??到包含 _someTextDescription 的行。这是为了处理该字段可能为空的情况,在这种情况下,我们存储一个空字符串。
对于大多数较小的脚本来说,这种使用存储的方法应该足够了。