我有一个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.
但是,这并不理想,因为我不想要依靠UNDOC并且我肯定不想强迫用户这样做。
我该如何有效地抛出一个错误,防止用户尝试从我的班级串行化对象?
按要求,最低例子重现情况:
% 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
不。我的代码不会抛出错误,即使我调用'error',我的代码也会抛出警告。 – gerrit 2013-03-18 12:30:10
并且将呼叫更改为警告并不能解决问题吗? – 2013-03-18 17:08:57
问题是我不能抛出错误,因为Matlab会将错误更改为警告。将其更改为警告并不能解决无法抛出错误的问题。 – gerrit 2013-03-18 18:19:00