How to make function available for several classes
6 ビュー (過去 30 日間)
古いコメントを表示
My problem is that I'm using one-liner functions like
isint = @(x) all(imag(x)==0 & mod(x, 1)==0);
to check the type of function inputs (this is similar to some answer of Bruno Luong somewhere on matlabcentral). Initially there was only one 'start' function to check this.
Now I'd like to use them in set methods of multiple classes, in which I'd like to check the validity of an input before assigning it to a property. But then it seems that it's needed to define these "checker functions" in each class or to abandon their use alltogether and write the underlying expressions directly into setters. Is there any elegant way to avoid these two unpleasant alternatives? May be somehow make the "checker functions" available to several classes (writing a separate function file for each checker is unpleasant as well..)?
0 件のコメント
採用された回答
Image Analyst
2015 年 12 月 23 日
You can define a static class that all your other classes then call to validate inputs to them. For example I have a static class for Excel ActiveX utilities. It starts out like this:
classdef Excel_utils
methods(Static)
% --------------------------------------------------------------------
% GetNumberOfExcelSheets: returns the number of worksheets in the active workbook.
% Sample call
% numberOfSheets = Excel_utils.GetNumberOfExcelSheets(Excel);
function numberOfSheets = GetNumberOfExcelSheets(excelObject)
try
worksheets = excelObject.sheets;
numberOfSheets = worksheets.Count;
catch ME
errorMessage = sprintf('Error in function %s() at line %d.\n\nError Message:\n%s', ...
ME.stack(1).name, ME.stack(1).line, ME.message);
fprintf(1, '%s\n', errorMessage);
WarnUser(errorMessage);
end
return; % from GetNumberOfExcelSheets()
end % of GetNumberOfExcelSheets()
and then after that it has a bunch more functions in it. Then whenever I want to call that method, I just do
numberOfSheets = Excel_utils.GetNumberOfExcelSheets(Excel);
I don't need to instantiate an object in advance to use the method since it's static. You could have a static class called ValidateInputs() and then have all the various methods listed inside that. Would that work for you?
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Software Development Tools についてさらに検索
製品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!