Call class A method from class B using function handle?

조회 수: 7 (최근 30일)
SoderlingPotro
SoderlingPotro 2022년 12월 11일
편집: SoderlingPotro 2022년 12월 12일
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

채택된 답변

Matt J
Matt J 2022년 12월 11일
function obj = MainClass()
obj.Prop1 = ClassB;
obj.Prop1.SetMethod(@()obj.MyMethod);
end
  댓글 수: 3
Matt J
Matt J 2022년 12월 12일
obj.Prop1.SetMethod(@(arg1)obj.MyMethod(arg1))
SoderlingPotro
SoderlingPotro 2022년 12월 12일
편집: SoderlingPotro 2022년 12월 12일
Got it, thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Linear Algebra에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by