构造时设置属性值
此示例说明如何定义 System object™ 构造函数并允许其接受名称-值属性对组作为输入。
将属性设置为使用名称-值对组输入
定义 System object 构造函数,该函数是一种与类(此示例中为 MyFile
)同名的方法。在该方法内,使用 setProperties
方法来设置所有公共属性,使它们可在用户构造对象时用于输入。nargin
是一个 MATLAB® 函数,用于确定输入参量的数目。varargin
指示对象的所有公共属性。
methods function obj = MyFile(varargin) setProperties(obj,nargin,varargin{:}); end end
包含构造函数设置的完整类定义文件
classdef MyFile < matlab.System % MyFile write numbers to a file % These properties are nontunable. They cannot be changed % after the setup method has been called or while the % object is running. properties (Nontunable) Filename ="default.bin" % the name of the file to create Access = 'wb' % The file access character vector (write, binary) end % These properties are private. Customers can only access % these properties through methods on this object properties (Hidden,Access = private) pFileID; % The identifier of the file to open end methods % You call setProperties in the constructor to let % a user specify public properties of object as % name-value pairs. function obj = MyFile(varargin) setProperties(obj,nargin,varargin{:}); end end methods (Access = protected) % In setup allocate any resources, which in this case is % opening the file. function setupImpl(obj) obj.pFileID = fopen(obj.Filename,obj.Access); if obj.pFileID < 0 error("Opening the file failed"); end end % This System object writes the input to the file. function stepImpl(obj,data) fwrite(obj.pFileID,data); end % Use release to close the file to prevent the % file handle from being left open. function releaseImpl(obj) fclose(obj.pFileID); end end end