【发布时间】:2023-03-20 07:46:01
【问题描述】:
与许多其他 OOP 语言一样,常量属性是 Matlab 中的静态属性(属于类,而不是实例)。访问它们的自然方式是ClassName.PropName,如Matlab documentation。
但是,在这样的场景中,我找不到从超类执行 ClassName.PropName 的方法:
classdef (Abstract) Superclass < handle
properties(Dependent)
dependentProperty
end
properties (Abstract, Constant)
constantProperty
end
methods
function result = get.dependentProperty(obj)
c = class(obj); % Here I have to get class of obj
result = length(c.constantProperty); % to use here as `ClassName.PropName`
end
end
end
classdef Subclass < Superclass
properties (Constant)
constantProperty = [cellstr('a'); cellstr('b')];
end
end
因此以下命令会导致以下输出:(预期输出)
>> subclassInstance = Subclass()
subclassInstance =
Subclass with properties:
constantProperty: {2×1 cell}
dependentProperty: 2
>> subclassInstance.dependentProperty
ans =
2
>>
但相反,我得到了以下信息:(实际输出)
>> subclassInstance = Subclass()
subclassInstance =
Subclass with properties:
constantProperty: {2×1 cell}
>> subclassInstance.dependentProperty
Struct contents reference from a non-struct array object.
Error in Superclass/get.dependentProperty (line 13)
result = length(c.constantProperty);
>>
还尝试过:c = metaclass(obj) 给出“没有适当的方法、属性或字段‘constantProperty’
类'meta.class'。”
问题:有没有办法从超类中获取对象的类,以便能够写出像ClassName.PropName这样的语句?
编辑:
我知道我可以像这样从对象引用中到达:
function result = get.dependentProperty(obj)
result = length(obj.constantProperty);
end
但这不是我想要的,因为它让读者认为constantProperty 是一个实例属性。这也没有在 Matlab 中记录,而是在文档中说 ClassName.PropName,这让我认为必须有办法。
【问题讨论】:
标签: matlab oop superclass static-variables