Common get and set methods for dynamic properties in user defined classes

3 ビュー (過去 30 日間)
Rajmohan
Rajmohan 2022 年 5 月 18 日
編集済み: Paras Gupta 2023 年 10 月 16 日
The matlab documentation shows how to define get and set functions for dynamic properties. Is it possible to defiine get and set methods that are common to several dynamic properties?

回答 (1 件)

Paras Gupta
Paras Gupta 2023 年 10 月 16 日
編集済み: Paras Gupta 2023 年 10 月 16 日
Hi Rajmohan,
I understand that you are want to have common set and get methods for several dynamic properties in a MATLAB class.
You can use the 'addlistener' function along with the 'PostSet' event to define a common set method, and the 'addlistener' function with the 'PostGet' event to define a common get method.
The following example code illustrates how to achieve the same:
classdef Car1 < handle
% The properties need to be defined as SetObservable and GetObservable
properties (SetObservable, GetObservable)
Brand
Model
end
methods
function obj = Car1(brand, model)
obj.Brand = brand;
obj.Model = model;
addlistener(obj, 'Brand', 'PostSet', @obj.commonSetMethod);
addlistener(obj, 'Model', 'PostSet', @obj.commonSetMethod);
addlistener(obj, 'Brand', 'PostGet', @obj.commonGetMethod);
addlistener(obj, 'Model', 'PostGet', @obj.commonGetMethod);
end
function commonSetMethod(obj, ~, ~)
disp('Common set method called');
end
function commonGetMethod(obj, ~, ~)
disp('Common get method called')
end
end
end
You can try running the following commands to see that the 'commonSetMethod' and 'commonGetMethod' are being executed for both the properties 'Brand' and 'Model'.
car = Car1('Brand1', 'Model1');
car.Brand = 'Brand2';
car.Model = 'Model2'
disp(car.Brand);
disp(car.Model);
Please refer to the following documentation links for more information on the functions used in the code above:
Hope this resolves your query.

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by