我刚开始使用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我想明确指定 HeaderLength 和 PayloadLength 都是uint16和 PacketType 是一个字符串。有办法吗?
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?
推荐答案有一个文档语法以强制实施属性类型:
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'.据我所知,这种语法支持所有原始类型,如: char,int 32,double,struct,cell,... ,除了任何用户定义的(只使用任何类名)。
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).
请注意,设置类型如上所示似乎是重写任何set方法如果有。
Note that setting the type as above seems to override any "set method" if any.
我刚刚遇到这个语法正在使用的内部类在R2013a toolboxdir('matlab')\graphics\+graphics\+internal\+figfile\@FigFile\FigFile.m ),但它也工作在R2012a,可能更旧的版本...以及
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...
更多推荐
我可以在MATLAB中将类型分配给类属性吗?
发布评论