我有一个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
答案 0 :(得分:3)
就个人而言,我更喜欢将所有属性标记为Transient
,并让对象有效地具有无效状态,这是保存/加载的结果。要防止MATLAB保存数据非常困难,而且您的解决方法可能会严重干扰用户的工作流程。
答案 1 :(得分:-1)
您的代码实际上会引发错误,您应该通过error()
替换warning()
的来电