Generic get/set methods for class properties
조회 수: 39 (최근 30일)
이전 댓글 표시
I've got some classes with loads of properties, all of which need a get/set method. Apart from the property names, the get/set methods are all identical. Is there any way to write a single generic get and set method that can parse the property name and act accordingly?
So for example, if my class currently looks something like this:
classdef testClass < handle
properties(Access = private)
privateProp1
privateProp2
end
properties(Dependent)
Prop1
Prop2
end
methods
function val = get.Prop1(obj)
val = obj.privateProp1;
end
function val = get.Prop2(obj)
val = obj.privateProp2;
end
end
end
Is there some way to just have a single version of the get method? In my head it would look something like this, but obviously this doesn't work:
function val = get.(propname)(obj)
val = obj.(['private', propname]);
end
It needs to work with dot notation, e.g.:
myClass = testClass;
var = testClass.Prop1;
I'm just trying to avoid defining dozens of near identical get and set methods, but I suspect there is no way round this.
Thanks
댓글 수: 0
답변 (3개)
Steven Lord
2021년 6월 30일
If all you're doing in your generic get and set methods are accessing the properties, you don't really need them. Just use dot indexing like this and the normal indexing will do the right thing:
myClass = testClass;
var = myClass.Prop1;
If you do need something like this to work:
get(myClass, 'Prop1')
Marco
2023년 4월 27일
You can try to inherit from both handle class and matlab.mixin.SetGet class.
classdef myClass < handle & matlab.mixin.SetGet
It worked for my purpose, hope it could help somebody.
댓글 수: 0
Benjamin Kraus
2023년 4월 27일
편집: Benjamin Kraus
2023년 4월 27일
You may be able to do something like this by implementing subsref (and/or subsasgn), but it isn't for the faint of heart.
Using subsref and subsasgn you can redifine how your object responds to all types of references, including the "dot assignment" and "dot references" (and parentheses, and curly braces).
However, by overloading subsref you are taking over all references (dot, parentheses, and braces), and handling all cases can be a challenge.
However, I would caution that, once you look at the sample code, you may just choose to switch back to copy/pasted get and set methods.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Customize Object Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!