Can I assign types to class properties in MATLAB?

后端 未结 3 1618
死守一世寂寞
死守一世寂寞 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:32

    The "Restrict Property Values to Specific Classes" feature is now officially supported since R2016a. It works similarly the old undocumented syntax, described in Amro's answer.

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

    Compatibility with previous versions

    R2016a supports both syntax options, I've noticed no differences between them. However, they both work slightly different from the "@"-based syntax in R2015b:

    1. In R2015b, an object myProp of a class MyPropClass2, inherited from MyPropClass1, perfectly passes the "class restriction" check, and then is stored "as is". So, the whole thing works just like an explicit isa(newPropVal,MyPropClass1) check added to a property set method MyPropClass1

    2. In case of R2016a "Restrict Property Values to Specific Classes" syntax, Matlab converts said object to the specified class. This would require an appropriate constructor for MyPropClass1, and means that MyPropClass1 could not be Abstract.

    Example:

    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
            someprop@MyPropClass1
        end   
    end
    
    ------------------------------------------------------------
    myObj = MyObjClass();
    myObj.someprop = MyPropClass2;
    
    % The following displays "MyPropClass1" in R2016a, and "MyPropClass2" in R2015b
    disp(class(myObj.someprop));
    

    Compatibility with class hierarchies

    In both R2016a and R2015b, the "Restrict Property Values to Specific Classes" qualifiers could not be re-defined in nested classes. E.g. it is not possible to define something like:

    classdef MyObjClass2 < MyObjClass  
        properties
            someprop@MyPropClass2
        end   
    end
    

提交回复
热议问题