2011-08-25 123 views
12

我刚刚使用MATLAB作为面向对象的环境,并且正在写第一个类来描述网络数据包。一个简单的例子是以下我可以将类型分配给MATLAB中的类属性吗?

classdef Packet 

    properties 
     HeaderLength 
     PayloadLength 
     PacketType 
    end 

end 

我想明确指定HeaderLengthPayloadLength都是UINT16的和PacketType是一个字符串。有没有办法做到这一点?

回答

20

存在着一个undocumented syntax执行物业类型:

classdef Packet 
    properties 
     [email protected] 
     [email protected] = uint16(0); 
     [email protected] 
    end 
end 

如果您尝试设置了错误类型的属性,你会得到一个错误:

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

据我所知,此语法支持所有基本类型,如:char, int32, double, struct, cell, ...,除了任何用户定义的(只使用任何类名)。

请注意,如上所述设置类型似乎会覆盖任何“设置方法”(如果有)。

我只是碰到这种语法在R2013a一个内部类(toolboxdir('matlab')\graphics\+graphics\+internal\+figfile\@FigFile\FigFile.m)被使用来了,但它也曾在R2012a,可能更早的版本,以及...

+0

这是一个整洁的发现! – Jonas

+6

[交叉引用](http://undocumentedmatlab.com/blog/setting-class-property-types) –

+1

@YairAltman:再次感谢您在博客上发布了一篇专门文章 – Amro

6

由于无法在Matlab中明确指定变量的类型,所以在声明属性时不能这样做。

但是,您可以定义一个set方法来检查类,并引发错误或将输入转换为任何您想要的。

例如

classdef myClass 
    properties 
     myProperty = uint16(23); %# specify default value using correct type 
    end 
    methods 
     function obj = set.myProperty(obj,val) 
     if ~isa(val,'uint16') 
      error('only uint16 values allowed') 
     end 
     %# assign the value 
     obj.myProperty = val; 
     end 
    end 
end 
+0

这样想。谢谢。 – Phonon

6

的“Restrict Property Values to Specific Classes”功能现在正式支持since R2016a。它的工作方式类似于Amro's answer中描述的旧的未记录语法。

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

与以前的版本

R2016a支持语法选项的兼容性,我注意到他们之间没有差异。然而,他们都工作从“@”略有不同 - 基于语法R2015b:

  1. 在R2015b,对象类MyPropClass2myProp,从MyPropClass1继承,完全可以通过“限制等级”查了,然后按“原样”存储。所以,整个事情的作品,就像一个明确的isa(newPropVal,MyPropClass1)检查添加到一个属性集方法MyPropClass1

  2. 在R2016a的情况下,“限制属性值特定的类”语法,MATLAB把上述对象到指定的类。这将需要MyPropClass1的适当构造函数,并且意味着MyPropClass1不能是Abstract

实施例:

classdef MyPropClass1  
    methods 
     % The following method is only used in R2016a case 
     function obj=MyPropClass1(val)    
     end 
    end   
end 

------------------------------------------------------------ 
classdef MyPropClass2 < MyPropClass1  
end 

------------------------------------------------------------ 
classdef MyObjClass  
    properties 
     [email protected] 
    end 
end 

------------------------------------------------------------ 
myObj = MyObjClass(); 
myObj.someprop = MyPropClass2; 

% The following displays "MyPropClass1" in R2016a, and "MyPropClass2" in R2015b 
disp(class(myObj.someprop)); 

与类层次结构的兼容性

在这两种R2016a和R2015b,“限制的属性值,以特定的类”限定符不能嵌套重新定义类。例如。这是不可能的定义如下:

classdef MyObjClass2 < MyObjClass 
    properties 
     [email protected] 
    end 
end 
相关问题