5

Confer the following code:

classdef highLowGame
    methods(Static)
        function [wonAmount, noGuesses] = run(gambledAmount)
            noGuesses = 'something';
            wonAmount = highLowGame.getPayout(gambledAmount, noGuesses); % <---
        end
        function wonAmount = getPayout(gambledAmount, noGuesses)
            wonAmount = 'something';
        end
    end
end

Is there a way to call a static method of the same class (inside a static) method without having to write the class name? Something like "self.getPayout(...)" - in case the class turns out to get to 500 lines and I want to rename it.

4

2 に答える 2

7

classdef質問への直接の回答ではありませんが、ファイルのブロックの末尾に「ローカル関数」を配置することもできますclass.m。これらはプライベートな静的メソッドのように動作しますが、クラスを使用して呼び出す必要はありません。名前。いえ

% myclass.m
classdef myclass
  methods ( Static )
    function x = foo()
      x = iMyFoo();
    end
  end
end
function x = iMyFoo()
  x = rand();
end
% end of myclass.m
于 2012-11-22T07:02:18.900 に答える
4

私が知る限り、「いいえ」と「しかし」です。通常、静的メソッドはクラス名でのみ指定できます。ただし、MATLAB には feval があるため、制限を回避する方法を偽造することができます。

classdef testStatic

    methods (Static)
        function p = getPi()  %this is a static method
            p = 3.14;
        end
    end

    methods
        function self = testStatic()

            testStatic.getPi  %these are all equivalent
            feval(sprintf('%s.getPi',class(self)))
            feval(sprintf('%s.getPi',mfilename('class')))
        end
    end
end

ここで、class(self) と mfilename は両方とも「testStatic」と評価されるため、上記の関数は「testStatic.getPi」を評価することになります。

または、非静的メソッド self.callStatic を作成することもできます。その後、常にそれを使用します。その中で、testStatic.getPi を呼び出すだけです。次に、その 1 行を変更するだけです。

于 2012-11-21T22:45:14.347 に答える