Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

oop - Can I assign types to class properties in MATLAB?

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

classdef Packet

    properties
        HeaderLength
        PayloadLength
        PacketType
    end

end

I would like to explicitly specify that HeaderLength and PayloadLength are both uint16's and PacketType is a string. Is there a way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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')[email protected]), but it also worked in R2012a, probably older versions as well...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...