2

我有一个 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.) 

我可以使用未记录的功能将警告变成错误:

>> 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 
4

2 回答 2

3

就个人而言,我更喜欢将所有属性标记为Transient,并让对象有效地具有无效状态,这是保存/加载的结果。阻止 MATLAB 保存您的数据非常困难,而且您的解决方法可能会严重干扰用户的工作流程。

于 2013-03-18T11:53:16.687 回答
-1

您的代码实际上引发了错误,您应该将您的调用替换error()warning()

于 2013-03-18T11:43:22.877 回答