5

授予以下代码:

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

有没有办法调用同一个类的静态方法(在静态方法中)而不必写类名?像“self.getPayout(...)”这样的东西——以防类结果达到 500 行并且我想重命名它。

4

2 回答 2

7

不是直接回答您的问题,但值得注意的是,您还可以classdef在文件中的块结束之后放置“本地函数”,这些函数的class.m行为类似于私有静态方法,但您不需要使用类调用它们姓名。IE

% 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。然后你只需要改变那一行。

于 2012-11-21T22:45:14.347 回答