常量屬性是Matlab中的靜態屬性(屬於類,而不是實例),就像許多其他OOP語言一樣。和自然的方式來訪問他們是ClassName.PropName
在Matlab documentation。在Matlab中從超類獲取對象的類
不過,我不能找到一種方法,從超做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文檔告訴我,我可以從類參考。另外,從對象到達是醜陋的,使讀者認爲'constantProperty'是一個實例屬性。另外,在Java中,這可以通過'this.getClass()'來實現,這讓我認爲必須有一種方法。 – ferit
我已經更新了我的答案。希望這有助於更好地解釋事情。 tl; dr:有一種方式,但這不是要走的路。使用這個對象,盧克! –
https://www.mathworks.com/help/matlab/matlab_oop/matlab-vs-other-oo-languages.html表示「不支持靜態屬性。請參閱持久變量。**對於Java靜態final或C++靜態常量屬性,使用常量屬性。**請參閱常量值屬性「。但是'findobj'方法更加醜陋,我最好使用對象引用。 – ferit