我有一个 Matlab 类,其中实现序列化和反序列化会很痛苦,而且不需要。
因此,我重载了 saveobj
如下:
function sobj = saveobj(self)
sojb = [];
error(['atmlab:' mfilename ':nostoring'], ...
['You tried to store %s %s. Loading is impossible, ' ...
'therefore I refuse to store. Sorry.'], ...
class(self), self.name);
end
不幸的是,当我测试这个时,Matlab 试图提供帮助并将警告变成错误(由于某种原因两次):
>> save('/tmp/test.mat', 'X')
Warning: While saving an object of class 'SatDataset':
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry.
(Type "warning off atmlab:SatDataset:nostoring" to suppress this warning.)
Warning: While saving an object of class 'SatDataset':
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry.
(Type "warning off atmlab:SatDataset:nostoring" to suppress this warning.)
我可以使用undocumented feature将警告变成错误:
>> warning error atmlab:SatDataset:nostoring
>> save('/tmp/test.mat', 'X')
Error using save
While saving an object of class 'SatDataset':
You tried to store SatDataset amsua. Loading is impossible, therefore I refuse to store. Sorry.
Unexpected error status flag encountered. Resetting to proper state.
但这并不令人满意,因为我不想依赖未记录的功能,而且我当然不想强制用户这样做。
如何有效地抛出错误,防止用户尝试从我的类中序列化对象?
根据要求,重现情况的最小示例:
% in TestClass.m
classdef TestClass < handle
methods
function sobj = saveobj(self)
sojb = [];
error('Unable to store %s objects', class(self));
end
end
end
% on the interactive prompt:
>> t = TestClass();
>> save('/tmp/fubar.mat', 't');
Warning: While saving an object of class 'TestClass':
Unable to store TestClass objects
Warning: While saving an object of class 'TestClass':
Unable to store TestClass objects
最佳答案
就个人而言,我更喜欢将所有属性标记为Transient
,并让对象有效地具有作为保存/加载结果的无效状态。阻止 MATLAB 保存您的数据非常困难,而且您的解决方法可能会严重干扰用户的工作流程。
关于matlab - 防止序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15475363/