假设我们有一个名为 MyClas 的 Matlab 类,如下所示,
classdef MyClass
properties
Value
end
methods
function foo(input1, input2)
...
end
end
end
我正在寻找的是 MyClass.anyThing(inputValue)
,其中 anyThing
和 inputValue
是任意字符串,anyThing
不是 MyClass
中定义的方法,将 anyThing
和 inputValue
作为两个字符串传递给我的 foo
功能。
换句话说,我希望能够通过将未定义的方法的名称和输入作为字符串传递给函数/方法来处理它们。
我很难详细说明我的问题,因为我不知道是否有任何技术术语可以描述我在这里想要实现的目标。然而,我设法找到了this link from math works ,它只是自定义索引操作,并不能完全解决我的问题。
最佳答案
您可以通过破解 subsref
的实现来模拟这一点。像这样:
classdef MethodRedirector
methods
function varargout = subsref(obj, S)
if numel(S) == 2 && strcmp(S(1).type, '.') && ...
strcmp(S(2).type, '()')
% Looks like obj.method(args)
fprintf('In method invocation to: %s with args:\n', S(1).subs);
celldisp(S(2).subs);
else
[varargout{1:nargout}] = builtin('subsref', obj, S);
end
end
end
end
限制是调用者必须使用 obj.method(args...)
语法,并且不能使用(通常等效的)method(obj, args...)
语法。
实际情况如下:
>> mr = MethodRedirector; mr.someMethod(1, '2', magic(3))
In method invocation to: someMethod with args:
ans{1} =
1
ans{2} =
2
ans{3} =
8 1 6
3 5 7
4 9 2
关于matlab - 通过将方法的名称和输入传递给函数/方法来处理 Matlab 中未定义的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60997252/