是否可以在不先分配给临时变量的情况下使用从函数返回的对象句柄的属性?
我有一个函数返回实例化对象的句柄。类似这样的事情:
function handle = GetHandle()
handle = SomeHandleClass();
end
我希望能够像用 C 语言编写程序一样使用返回值:
foo = GetHandle().property;
但是,当 MATLAB 尝试解析它时,我收到一个错误:
??? Undefined variable "GetHandle" or class "GetHandle".
我可以让它工作的唯一方法没有错误的方法是使用临时变量作为中间步骤:
handle = GetHandle();
foo = handle.property;
是否有一个简单而优雅的解决方案,或者这对于 MATLAB 的语法来说根本不可能?
I have a function that returns a handle to an instantiated object. Something like:
function handle = GetHandle()
handle = SomeHandleClass();
end
I would like to be able to use the return value like I would if I was writing a program in C:
foo = GetHandle().property;
However, I get an error from MATLAB when it tries to parse that:
??? Undefined variable "GetHandle" or class "GetHandle".
The only way I can get this to work without an error is to use a temporary variable as an intermediate step:
handle = GetHandle();
foo = handle.property;
Is there a simple and elegant solution to this, or is this simply impossible with MATLAB's syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要定义静态属性,您可以使用 CONSTANT 关键字(感谢,@Nzbuu)
这是 MathWorks 的一个示例(修复了一些错误):
常量属性作为
className.propertyName
访问,例如NamedConst.R
。每当第一次加载类时(Matlab 启动后,或清除类
后),都会设置属性的值。因此,只要您不调用clear classes
,NamedConst.RN
就会在整个会话期间保持不变。To define static properties, you can use the CONSTANT keyword (thanks, @Nzbuu)
Here's one example from MathWorks (with some errors fixed):
Constant properties are accessed as
className.propertyName
, e.g.NamedConst.R
. The values of the properties are set whenever the class is loaded for the first time (after the start of Matlab, or afterclear classes
). Thus,NamedConst.RN
will remain constant throughout a session as long as you don't callclear classes
.嗯,我不想反对乔纳斯和他的 21.7k 点,但我认为你可以使用 hgsetget 句柄类而不是普通的句柄类,然后使用get 函数。
然后你可以使用 get 函数来获取属性:
编辑:它并不完全像 C,但非常接近。
Hmm, I don't like to disagree with Jonas and his 21.7k points, but I think you can do this using the hgsetget handle class instead of the normal handle class, and then using the get function.
Then you can use the get function to get the property:
EDIT: It is not excactly like C, but pretty close.
在 MATLAB 中拥有静态属性的唯一方法是作为常量:
然后
someHandleClass.myProperty
将返回3
。The only way to have a static property in MATLAB is as a constant:
then
someHandleClass.myProperty
will return3
.