Contenido principal

Establecer los valores de las propiedades en el momento de la construcción

R2026b

En el siguiente ejemplo se muestra cómo definir un constructor de System object™ y permitir que acepte pares de propiedades nombre-valor como entrada.

Establecer las propiedades para usar una entrada de par nombre-valor

Defina el constructor de System object, que es un método con el mismo nombre que la clase (MyFile en este ejemplo). Dentro de ese método, se utiliza el método setProperties para que todas las propiedades públicas estén disponibles para la entrada cuando el usuario construye el objeto. nargin es una función de MATLAB® que determina el número de argumentos de entrada. varargin indica todas las propiedades públicas del objeto.

methods 
   function obj = MyFile(varargin)
      setProperties(obj,nargin,varargin{:});
   end
end

Archivo de definición de clase completo con la configuración del constructor

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

Consulte también

|

Temas