首页 > 解决方案 > 访问 Matlab 类属性(又名常量)

问题描述

我有一些类,我为其创建了几个常量属性。这是一些示例代码:

classdef genericClassName < handle
    properties (Constant)
        Name = 'genericClassName'
        Description = 'description of the class'
    end
...

在主代码中,我通过分配类句柄来创建对象,在这种情况下,类句柄来自一个单独的函数传递的预分配值。这就像

fuctionModel = @genericClassName;

稍后我将创建其他对象并将functionModel的值传递给这些类。到目前为止,一切正常。

Matlab 文档说这些常量属性的访问方式如下:

genericClassName.Name
genericClassName.Description

我可以在命令行中输入它,它会产生所需的结果,给出NameDescription属性的值 - 与分配给常量属性的值相同。但是,我只有句柄,它作为@genericClassName保存在functionModel中。

这是我的问题:当我只有句柄时,如何引用这个类及其常量属性,并在前面加上它的 at 符号?

更新 缺少更简单或简洁的答案,@Edric 和@CrisLuengo 的答案组合似乎有效。例如:

mc=meta.class.fromName(func2str(functionalModel));
result = eval([mc.Name '.Description']);

将名称为Description的常量放入变量result中。这可用于我需要的东西,我可能只是将它包装成一个函数。

标签: matlabclassclass-properties

解决方案


嗯,如果您只有构造函数方法的句柄,并且希望避免构造实例(MATLAB 允许您Constant从实例访问属性),那么您可以使用meta.class.fromName.

fh = @genericClassName;
% Get the metaclass from the constructor
mc = meta.class.fromName(func2str(fh));
% Find the property named 'Name'
idx = strmatch('Name', {mc.PropertyList.Name})
% Get the default (Constant) value
mc.PropertyList(idx).DefaultValue

推荐阅读