1

我正在尝试创建一个 Matlab 类,其中方法属性在类构造函数中进行了更改。这样做的目的是隐藏/使某些方法可见,具体取决于类输入。

例如:

classdef  (HandleCompatible) myClass < dynamicprops & handle % & hgsetget
properties (Hidden)
    myProp
end
methods (Hidden)
    function obj = myClass(input)
        %class constructor
        %add some dynamic properties
        switch input
            case 1
                %unknown code:
                %make myMethod1 visible
            case 2

                %unknown code:
                %make myMethod2 visible
            otherwise
                %unknown code:
                %make myMethod1 visible
                %make myMethod2 visible
        end
    end
end

methods (Hidden)
    function myMethod1 (obj, input)
        %function...
    end
    function output = myMethod2(obj, input)
        %function...
    end
end
end

我尝试使用以下内容:

mco = metaclass(obj);
mlist = mco.MethodList;
mlist(myMethod1Index).Hidden = false;

,但我收到以下错误:

不允许设置“meta.method”类的“隐藏”属性。


感谢你的回复。

如果我需要在类构造函数中选择性地访问我的方法,这可能是一个解决方案。不过,我需要在我的程序中使用这些方法,并在选项卡完成时让它们可见或不可见:

%Obj1
myObj1 = myClass (inputs, '-1');
myObj1.myMethod1(arg);
%myObj1.myMethod2 - hidden


%Obj2
myObj2 = myClass (inputs, '1');
%myObj2.myMethod1 - hidden
value1 = myObj2.myMethod2(arg);


%Obj3
myObj3 = myClass (inputs, '0');
myObj3.myMethod1(arg);
value2 = myObj3.myMethod2(arg); 
%here i want to be able to access both methods

也许可以在类构造函数期间选择方法属性并更改属性。但这必须在不使用元类的情况下完成

4

1 回答 1

1

Why not expose only a factory method and build instances of different classes depending on the input? You can use access qualifiers to lock things down like so:

% a.m
classdef a
    properties, a_thing, end
    methods ( Access = ?factory )
        function obj = a()
        end
    end
end

% b.m
classdef b
    properties, b_thing, end
    methods ( Access = ?factory )
        function obj = b()
        end
    end
end

% factory.m
classdef factory
    methods ( Static )
        function val = build(arg)
            if isequal(arg, 'a')
                val = a;
            else
                val = b;
            end
        end
    end
 end
于 2012-09-18T15:22:50.647 回答