是否可以在不首先分配临时变量的情况下使用从函数返回的对象句柄的属

是否可以在不首先分配临时变量的情况下使用从函数返回的对象句柄的属

本文介绍了是否可以在不首先分配临时变量的情况下使用从函数返回的对象句柄的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回实例化对象句柄的函数.像这样:

I have a function that returns a handle to an instantiated object. Something like:

function handle = GetHandle()
    handle = SomeHandleClass();
end

我希望能够像使用C语言编写程序那样使用返回值:

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;

但是,当我尝试解析该错误时,我从MATLAB中收到一个错误:

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;

是否有一个简单而优雅的解决方案,或者用MATLAB的语法根本不可能做到这一点?

Is there a simple and elegant solution to this, or is this simply impossible with MATLAB's syntax?

推荐答案

要定义静态属性,可以使用常量关键字(感谢@Nzbuu)

To define static properties, you can use the CONSTANT keyword (thanks, @Nzbuu)

这是MathWorks的一个示例(已修复一些错误):

Here's one example from MathWorks (with some errors fixed):

classdef NamedConst
   properties (Constant)
      R = pi/180;
      D = 1/NamedConst.R;
      AccCode = '0145968740001110202NPQ';
      RN = rand(5);
   end
end

常量属性以className.propertyName的形式访问,例如NamedConst.R.每当首次加载类时(在Matlab启动后或clear classes之后),都​​将设置属性的值.因此,只要您不呼叫clear classesNamedConst.RN在整个会话中都将保持不变.

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 after clear classes). Thus, NamedConst.RN will remain constant throughout a session as long as you don't call clear classes.

这篇关于是否可以在不首先分配临时变量的情况下使用从函数返回的对象句柄的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:50