我可以在MATLAB中将类型分配给类属性吗? [英] Can I assign types to class properties in MATLAB?

查看:207
本文介绍了我可以在MATLAB中将类型分配给类属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用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中将类型分配给类属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆