2

我有以下情况。在myClass.m我定义了

classdef myClass
    ...
    methods
        function y = foo(this, x)
            ...
        end
    end
end

然后我执行

obj = myClass();
nargin(@obj.foo)

结果是-1,而我期望为1。该函数仍然只接受一个参数。我实际上想将句柄传递给另一个检查参数数量的函数(我无权访问),并且我希望检查 nargin(f)==1 成功。有没有办法做到这一点?

PS我知道,如果我将方法定义为静态,我将通过调用获得正确的结果,nargin(@(x)Test.foo)但该方法访问类变量。

4

2 回答 2

2

即使这个问题得到了回答和接受,我认为值得展示一种工作方法,即使不创建类的实例也可以工作。参考元类:https ://ch.mathworks.com/help/matlab/ref/metaclass.html

metaClass = ?myClass
numArgIn = zeros(length(metaClass.MethodList), 1);
names = strings(length(metaClass.MethodList), 1);
for i=1:length(metaClass.MethodList)
    names(i) = string(metaClass.MethodList(i).Name);
    numArgIn(i) = numel(metaClass.MethodList(i).InputNames);
end
disp(numArgIn(names=="foo"))

当您创建包含类和一些模块的文件夹时,可以使用以下单行符号:

nargin('@myClass/foo.m')

在后一个示例中,可以删除文件结尾而没有效果。

于 2020-12-08T10:51:25.123 回答
0

我无法再验证此答案的有效性。查看更多最新答案和评论。

原始答案

我通过定义自己的包装器来解决问题,例如

function y = mywrapper(f, x)
%MYWRAPPER nargin(@(x)mywrapper(f, x)) is 1 as it should be
y = f(x);

end

我意识到 nargin(@(x)@obj.foo) 也做了我想要的

于 2013-11-09T09:03:33.817 回答