您不能像添加动态属性那样添加方法。但是,有两种方法可以在开发过程中实现新方法,不需要您每次都重新加载数据。
(1) 我将标准方法编写为单独的函数,并在开发过程中将它们称为myMethod(obj)。一旦我确定它们是稳定的,我将它们的签名添加到类定义文件中——这当然需要clear classes,但它是一个延迟很大的,有时你可能不得不关闭 Matlab ,无论如何。
(2) 使用 set/get 方法,事情变得有点棘手。如果您使用dynamicprops 添加新属性,您也可以指定它们的 set/get 方法,但是(这些方法/函数很可能希望接收属性的名称,以便他们知道要引用什么):
addprop(obj,'new_prop');
prop = findprop(obj,'new_prop');
prop.SetMethod = @(obj,val)yourCustomSetMethod(obj,val,'new_prop')
编辑
(2.1) 下面是一个如何设置隐藏属性来存储和检索结果的示例(基于jmlopez' answer)。显然,如果您对实际设计的内容有更好的了解,这可以得到很大的改进
classdef myDynamicClass < dynamicprops
properties (Hidden)
name %# class name
store %# structure that stores the values of the dynamic properties
end
methods
function self = myDynamicClass(clsname, varargin)
% self = myDynamicClass(clsname, propname, type)
% here type is a handle to a basic datatype.
self.name_ = clsname;
for i=1:2:length(varargin)
key = varargin{i};
addprop(self, key);
prop = findprop(self, key);
prop.SetMethod = @(obj,val)myDynamicClass.setMethod(obj,val,key);
prop.GetMethod = @(obj)myDynamicClass.getMethod(obj,key);
end
end
function out = classname(self)
out = self.name_;
end
end
methods (Static, Hidden) %# you may want to put these in a separate fcn instead
function setMethod(self,val,key)
%# have a generic test, for example, force nonempty double
validateattributes(val,{'double'},{'nonempty'}); %# will error if not double or if empty
%# store
self.store.(key) = val;
end
function val = getMethod(self,key)
%# check whether the property exists already, return NaN otherwise
%# could also use this to load from file if the data is not supposed to be loaded on construction
if isfield(self.store,key)
val = self.store.(key);
else
val = NaN;
end
end
end
end