MATLAB - create reference (handle?) to variable

前端 未结 3 1539
北恋
北恋 2021-02-02 03:13

Suppose I have the following class:

classdef myClass < handle
    properties
        A = 1
    end
    methods
        function obj = myClass(val)
                   


        
3条回答
  •  孤城傲影
    2021-02-02 03:37

    You could do this by with a PropertyReference class

    classdef PropertyReference < handle
        %PropertyReference Reference to a property in another object    
        properties
            sourceHandle
            sourceFieldName
        end
    
        properties (Dependent = true)
             Value
        end
    
        methods                
            function obj = PropertyReference (source, fieldName)            
                obj.sourceHandle = source;
                obj.sourceFieldName = fieldName
            end
            function value = get.Value( obj )
                value = obj.sourceHandle.(obj.sourceFieldName);
            end
    
            function set.Value( obj, value )
                obj.sourceHandle.(obj.sourceFieldName) = value;
            end
            function disp( obj )
                disp(obj.Value);
            end
        end              
    end
    

    Continuing your example, you could then use PropertyReference as follows:

    q = myClass(10);
    >> q.A = 15;
    >> ref = PropertyReference(q,'A');
    >> disp(ref)
       15
    >> q.A = 42;
    >> disp(ref)
       42
    

    Usage of the PropertyReference class is a bit awkward but the original class remains unchanged.

    EDIT - Added disp function overload as per strictlyrude27 comment

提交回复
热议问题