• 5. The Storage String


    The Storage String


    有时您需要存储必须在重新加载或关闭游戏或重新编译脚本期间才能保存的信息。网格程序目前只提供一种方法来做到这一点:存储属性。此属性驻留在脚本的基类 MyGridProgram 中,因此可以通过脚本中的任何方法或属性访问 - 但不能直接通过任何子类访问(参见本页底部 - “网格终端系统和子类” - 一种方式来解决这个问题)。
    Storage 属性只是一个字符串属性:

    public void Save()
    {
        Storage = "My String"
    }
    
    • 1
    • 2
    • 3
    • 4

    如您所见,它的使用没有什么特别之处。此属性与任何其他属性之间的区别在于,它的内容在保存游戏时会保存到您的磁盘中。

    将其更改为任何旧字符串,这不是很有用,是吗。如果您需要保存更复杂的内容怎么办?好吧,恐怕你将不得不自己做艰苦的工作。

    在 Storage 中存储多个值的绝对最简单和原始的方法是使用 string concatenationstring.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
        );
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    注意在 Program() 中使用 int.TryParse。我们使用它是因为如果字符串包含我们不理解的内容,我们希望尽最大努力优雅地失败。如果我们更改字符串的格式,或者我们在保存过程中以某种方式出错,就会发生这种情况。安全总比后悔好。

    同样,请注意我们添加了 null-coalescing operator运算符 ??到包含 _someTextDescription 的行。这是为了处理该字段可能为空的情况,在这种情况下,我们存储一个空字符串。

    对于大多数较小的脚本来说,这种使用存储的方法应该足够了。

  • 相关阅读:
    AMD Ryzen 5 7600X 6-core/12-thread Raphael CPU【搬运外媒VedioCardz报道(手工翻译)】
    MySQL学习 [第一天] ——数据库的基本操作 Ⅰ
    【opencv】opencv开发包简介
    【c++入门(2)】搜索2
    【MySQL】IF、ISNULL、IFNULL、NULLIF 函数用法
    AMQP协议详解
    Django在Views视图内取消当前请求的@receiver(post_save, sender=xxxxxx)信号
    pytorch中常用的损失函数
    关于React中的数据源绑定
    [java] 字符串底层剖析与常见面试题
  • 原文地址:https://blog.csdn.net/qq_34942306/article/details/127735943