Property Validation fails due to assignment issues.
7 ビュー (過去 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.
0 件のコメント
回答 (1 件)
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.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Argument Definitions についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!