Property Validation fails due to assignment issues.

8 次查看(过去 30 天)
Hey everyone,
I'm trying to implement some property validation function for a class as follows
classdef test
properties
Str {mustBeString(Str)}
end
methods
function obj = test(str)
obj.Str = str;
end
end
end
function mustBeString(str)
% MUSTBESTRING checks if argument is a string
if ~isstring(str) && ~ischar(str)
error('Parameter:wrongType',...
'Description must be string.');
end
end
But here's the problem. It doesn't matter which value or type Str has, because matlab seems to assign an empty value for this property even before the constructor is evaluated. In fact I checked in debugging mode and it seems that the validation function is called before the constructor.
I also tried to execute a modified example from the matlab documentation
classdef ImData
properties
Data {mustBeNumeric, mustBeInRange(Data,[0,255])}
end
methods
function obj = ImData(dat)
obj.Data = dat;
end
end
end
function mustBeInRange(a,b)
if any(a(:) < b(1)) || any(a(:) > b(2))
error(['Value assigned to Data property is not in range ',...
num2str(b(1)),'...',num2str(b(2))])
end
end
In this case everything worked fine.
Anyone who might have an idea, how to fix this issue?
Thank you very much.

回答(1 个)

Nirav Sharda
Nirav Sharda 2017-4-18
The documentation page of Property Validation mentions that you should add a default value. Also in the example mentioned in the document they have set the default value of the Data which is numeric to 0. You can in your case set it to empty string or char array. You can modify your code to:
Str {mustBeString(Str)} = ''
I hope this helps.

类别

Help CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by