Info
此问题已关闭。 请重新打开它进行编辑或回答。
How to create OOP properties with subfileds
1 次查看(过去 30 天)
显示 更早的评论
Hi Anyone can explain me how to create an object like this (like a struct with fields):
properties
Name
Tasks
end
But inside the property task I should have properties like:
Tasks.Name
Tasks.Size
for which I can validateattributes and use the get and set methods (matlab.mixin.SetGet)
0 个评论
回答(2 个)
Adam
2016-1-26
Usually I do this by having Tasks also be an object of a class so that class will have the required properties.
You can do it with a struct though just as you would outside of a class. You cannot define the fields as such in the properties block (though I guess you can initialise to an empty struct with specified fields - I don't use structs so I haven't really tried this).
The fields of Tasks would then get created wherever you have the necessary data to put in them.
I think you would need to give more information what you are trying to do. I've never used matlab.mixin.SetGet as I tend to just use ordinary get and set functions that I write with a validateattributes at the start of all my set functions, but I don't see why it would be incompatible with what you are asking.
validating a struct for lots of fields is a pain though in general and is one of the reasons I almost exclusively use classes even if my class is effectively just a data structure with noting but public get and set functions that validate what is set. It means that in the example you give you don't need to validate struct fields because 'Tasks' would be an object of a class where the properties are clearly defined already.
0 个评论
Guillaume
2016-1-26
As Adam says, once you've gone OOP you may as well go OOP all the way and have Task an instance of another class. Otherwise, you can simply initialise your property as a structure:
classdef ClassName
properties
Name;
Task = struct('Name', [], 'Size', []);
end
You should also define a setter for the Task property otherwise it can just be replaced by anything after construction
methods (Access = public)
function this = set.Task(this, value)
assert(isstruct(value) && all(ismember(fieldnames(value), {'Name', 'Size'})));
this.Task = value;
end
end
end
2 个评论
Guillaume
2016-1-27
The warning about mixing handle and value class has nothing to do with using structures.
You do have to change the signature of the setter if the class is a handle class, though:
methods (Access = public)
function set.Task(this, value) %setter signature for a handle class
assert(isstruct(value) && all(ismember(fieldnames(value), {'Name', 'Size'})));
this.Task = value;
end
end
end
此问题已关闭。
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!