Main Content

将属性值限制为有限列表

如果要创建具有一组有限的可接受值的 System object™ 属性,您可以使用枚举或属性验证。

对于在 Simulink®MATLAB System 块中使用的 System object,您可以使用枚举或属性验证。如果使用枚举,枚举也可以从 Simulink.IntEnumType 派生。您可以使用此类型的枚举将自定义头等属性添加到 MATLAB System 模块的输入或输出。请参阅在 Simulink 模型中使用枚举数据 (Simulink)

使用 mustBeMember 进行属性验证

要使用属性验证来限制属性值,您可以使用 mustBeMember 验证函数。

以下示例定义一个 Style 属性,其值可以是 soliddashdot。默认值为 solid(1,1) 将属性定义为标量。

    properties
        Style (1,1) string {mustBeMember(Style, ["solid","dash","dot"])} = "solid";
    end
要支持不区分大小写的匹配,请改用 matlab.system.mustBeMember
    properties
        Style (1,:) char {matlab.system.mustBeMember(Style, ["solid","dash","dot"])} = "solid";
    end

枚举属性

要在 System object 中使用枚举数据,您应在 System object 类定义中引用枚举作为属性,并在单独的类定义文件中定义该枚举类。

要创建枚举属性,您需要:

  • 设置为枚举类的 System object 属性。

  • 关联的枚举类定义,用于为属性定义所有可能的值。

此示例为 System object 定义颜色枚举属性。枚举类 ColorValues 的定义如下:

classdef ColorValues < int32
    enumeration
        blue (0)
        red (1)
        green (2)
    end
end
ColorValues 类继承自 int32,以实现代码生成兼容性。枚举值必须是有效的 MATLAB 标识符

在 System object 中,Color 属性定义为 ColorValues 对象,blue 为默认值。(1,1)Color 属性定义为标量:

properties
   Color (1, 1) ColorValues = ColorValues.blue
end

创建 Whiteboard System object

此示例说明 Whiteboard System object™ 的类定义、两种类型的有限列表属性以及如何使用该对象。每次运行 Whiteboard 对象时,它都会在白板上绘制一条线。

Whiteboard System object 的定义

type Whiteboard.m
classdef Whiteboard < matlab.System
    % Whiteboard Draw lines on a figure window
    %
    
    
    properties(Nontunable)
        Color (1, 1) ColorValues = ColorValues.blue
        Style (1,1) string {mustBeMember(Style, ["solid","dash","dot"])} = "solid";
    end

    methods (Access = protected)
        function stepImpl(obj)
            h = Whiteboard.getWhiteboard();
            switch obj.Style
                case "solid"
                    linestyle = "-";
                case "dash"
                    linestyle = "--";
                case "dot"
                    linestyle = ":";
            end
            plot(h, randn([2,1]), randn([2,1]), ...
                "Color",string(obj.Color), "LineStyle",linestyle);
        end
        
        function releaseImpl(~)
            cla(Whiteboard.getWhiteboard());
            hold on
        end
    end
    
    methods (Static)
        function a = getWhiteboard()
            h = findobj('tag','whiteboard');
            if isempty(h)
                h = figure('tag','whiteboard');
                hold on
            end
            a = gca;
        end
    end
end

构造 System object。

greenInk = Whiteboard;
blueInk = Whiteboard; 

更改颜色并设置蓝色线型。

greenInk.Color = "green";
blueInk.Color = "blue";
blueInk.Style = "dot";

绘制几个线条。

for i=1:3
  greenInk();
  blueInk();
end

Figure contains an axes object. The axes object contains 6 objects of type line.

清空白板。

release(greenInk);
release(blueInk);

Figure contains an axes object. The axes object is empty.

相关主题