Call class A method from class B using function handle?
6 次查看(过去 30 天)
显示 更早的评论
Please see below example:
classdef MainClass
properties
Prop1
end
methods
function obj = MainClass()
obj.Prop1 = ClassB;
obj.Prop1.SetMethod(@MyMethod);
end
function MyMethod(obj)
disp('MainClass MyMethod called')
end
end
end
classdef ClassB < handle
properties
UpdateMethod
end
methods
function SetMethod(obj,newMethod)
obj.UpdateMethod = newMethod;
end
function CallUpdateMethod(obj)
obj.UpdateMethod();
end
end
end
>> x = MainClass;
>> x.Prop1.CallUpdateMethod;
Unrecognized function or variable 'MyMethod'.
Error in ClassB/CallUpdateMethod (line 10)
obj.UpdateMethod();
I'd like to call MainClass MyMethod from ClassB however am misunderstanding how this should be done. Any help would be appreciated. Thanks
0 个评论
采纳的回答
Matt J
2022-12-11
function obj = MainClass()
obj.Prop1 = ClassB;
obj.Prop1.SetMethod(@()obj.MyMethod);
end
3 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!