答案是获得@Pablo所示的函数句柄.
请注意,您的类应该从handle
类中派生,以使其正常工作(以便通过引用传递对象).
请考虑以下示例:
classdef hello < handle
properties
name = '';
end
methods
function this = hello()
this.name = 'world';
end
function say(this)
fprintf('Hello %s!\n', this.name);
end
end
end
Run Code Online (Sandbox Code Playgroud)
现在我们获得成员函数的句柄,并使用它:
obj = hello(); %# create object
f = @obj.say; %# get handle to function
obj.name = 'there'; %# change object state
obj.say()
f()
Run Code Online (Sandbox Code Playgroud)
输出:
Hello there!
Hello there!
Run Code Online (Sandbox Code Playgroud)
但是,如果我们将其定义为值类(将第一行更改为classdef hello
),则输出将不同:
Hello there!
Hello world!
Run Code Online (Sandbox Code Playgroud)
小智 6
人们也可以写
fstr = 'say';
obj.(fstr)();
Run Code Online (Sandbox Code Playgroud)
这具有以下优点:如果修改了对象(obj),则不需要句柄类.