Can I assign types to class properties in MATLAB?

后端 未结 3 1628
死守一世寂寞
死守一世寂寞 2020-12-14 20:48

I\'m new to using MATLAB as an object-oriented environment and I\'m writing my first class to describe a network packet. A simple example would be the following



        
3条回答
  •  盖世英雄少女心
    2020-12-14 21:20

    There exist an undocumented syntax to enforce property types:

    classdef Packet
        properties
            HeaderLength@uint16
            PayloadLength@uint16 = uint16(0);
            PacketType@char
        end
    end
    

    If you try to set a property with the wrong type, you get an error:

    >> p = Packet;
    >> p.PacketType = 'tcp';
    >> p.HeaderLength = 100;
    While setting the 'HeaderLength' property of Packet:
    Value must be 'uint16'.
    

    As far as I can tell, this syntax support all primitive types like: char, int32, double, struct, cell, ..., in addition to any user-defined ones (just use any class name).

    Note that setting the type as above seems to override any "set method" if any.

    I just came across this syntax being used in an internal class in R2013a (toolboxdir('matlab')\graphics\+graphics\+internal\+figfile\@FigFile\FigFile.m), but it also worked in R2012a, probably older versions as well...

提交回复
热议问题