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

回答(3 个)

Steven Lord
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')
have your handle class inherit from the matlab.mixin.SetGet class.
  1 个评论
Neil Casson
Neil Casson 2021-6-30
I haven't shown it in the example, but in the actual class I'm writing the get method does some conversions of data types and such like, so I can't really dispense with the get methods.
Using the matlab.mixin.SetGet approach also won't work, as it needs to be compatible with dot indexing

请先登录,再进行评论。


Marco
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.

Benjamin Kraus
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.
I'd start by checking out the doc page Code Patterns for subsref and subsasgn Methods.
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.

类别

Help CenterFile Exchange 中查找有关 Customize Object Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by