有人考虑过在 D 中实现某种自动数据(对象)持久化吗?我对这个问题的理想解决方案是这样的:
@persistent int x = 1;
这对于静态变量来说是最无缝的,但动态变量也是可能的。
这些变量将存储在键值存储数据库中。键可以是基于作用域变量名称和类型的指纹摘要以及当前加载代码的一些摘要。
最佳答案
您可以使用模板做一些类似的事情。看看这个:
import std.stdio;
// do not declare two of these on the same line or they'll get mixed up
struct persistent(Type, string file = __FILE__, size_t line = __LINE__) {
Type info;
alias info this;
// require an initializer
@disable this();
// with the initializer
this(Type t) {
// if it is in the file, we should load it here
// else...
info = t;
}
~this() {
// you should actually save it to the file
writeln("Saving ", info, " as key ",
file,":",line);
}
}
void main() {
persistent!int x = 10;
}
如果你运行它,你会看到初始化程序和写入,如果你填写了一个文件支持(可能是使用键和值的 json,或其他一些序列化程序来处理更多类型),它应该能够节省。您还可以将 dtor 保存到全局缓冲区,然后让模块析构函数将其实际保存到文件(并且模块构造函数也加载文件),这样它就不会在每次函数调用时尝试读/写文件。
所有变量都将表现为静态变量,因为您可以看到这里的关键是声明的文件和行号,没有环境输入。但是,嘿,它相当简单并且应该可以工作。
关于object - D 中的自动数据持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20932921/