oop - 如何在 MATLAB 中获取对象(类 inst)中的方法句柄

标签 oop class matlab methods

我试图从 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/

相关文章:

oop - 多态性如何使我的代码更灵活?

asp.net - 如何在我的代码中使用接口(interface)使其更具可扩展性?

java - 您可以使用泛型进行方法重载并且只更改方法签名的泛型类型吗?

java - 在Java中,变量名可以和类名相同

sql - 错误 'where clause' matlab 中使用字符串数组的未知列

matlab - 为 DE 系统实现 Runge-Kutta

c++ - 调用构造函数时出错

c++ - 使用自指针为类数据成员赋值时的区别

c++ - 如何访问从模板类继承的私有(private)静态类成员?

matlab - 交换仅对下对角线元素生效的行