Call class A method from class B using function handle?

6 Ansichten (letzte 30 Tage)
SoderlingPotro
SoderlingPotro am 11 Dez. 2022
Bearbeitet: SoderlingPotro am 12 Dez. 2022
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

Akzeptierte Antwort

Matt J
Matt J am 11 Dez. 2022
function obj = MainClass()
obj.Prop1 = ClassB;
obj.Prop1.SetMethod(@()obj.MyMethod);
end
  3 Kommentare
Matt J
Matt J am 12 Dez. 2022
obj.Prop1.SetMethod(@(arg1)obj.MyMethod(arg1))
SoderlingPotro
SoderlingPotro am 12 Dez. 2022
Bearbeitet: SoderlingPotro am 12 Dez. 2022
Got it, thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by