我试图从 MATLAB 中的对象中获取方法句柄,但 str2func('obj.MethodName') 之类的东西不起作用
最佳答案
答案是获取函数句柄 @Pablo已显示。
请注意,您的类应该派生自 handle
类才能正常工作(以便通过引用传递对象)。
考虑以下示例:
你好.m
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
现在我们得到成员函数的句柄,并使用它:
obj = hello(); %# create object
f = @obj.say; %# get handle to function
obj.name = 'there'; %# change object state
obj.say()
f()
输出:
Hello there!
Hello there!
但是,如果我们将其定义为 Value Class相反(将第一行更改为 classdef hello
),输出会有所不同:
Hello there!
Hello world!
关于oop - 如何在 MATLAB 中获取对象(类 inst)中的方法句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7628343/