我想實現一個可以提供給構造函數或可能在其他方法中生成的屬性的類。我不想將數據保存到磁盤或在加載時生成。我至今是:Matlab OOP調用get方法保存瞬態屬性。
classdef MyClass
properties(GetAccess = public, SetAccess = private)
Property1
Property2
Property3
end
properties(Access = private)
Property4
end
properties(Transient = true)
ProblemProperty
end
properties(Dependent = true, Transient = true)
Property5
end
methods
function MyClass
% Constructor.
end
function val = get.Property5(B)
val = SomeFunction(Property1);
end
function val = get.ProblemProperty(B)
if isempty(B.ProblemProperty)
B = GenerateProblemProperty(B);
end
val = B.ProblemProperty;
end
function B = GenerateProblemProperty(B)
B.ProblemProperty = AnotherFunction(B.Property2);
end
end
end
的問題是,當我嘗試將對象保存到磁盤,MATLAB調用get.ProblemProperty方法(通過只保存聲明運行探查證實)。 ProblemProperty字段爲空,我希望它保持原樣。它不調用get.Property5方法。
如何避免調用get.ProblemProperty?
我想過這個,但有時候這個值實際上是直接在構造函數中提供的。我可以在構造函數中爲依賴屬性設置值嗎? – MatlabSorter
@MatlabSorter - 我更新了我的答案,以允許傳遞給構造函數的可選自定義值。要點是使用私有屬性來存儲這個可選值,並使用get.ProblemProperty來決定是檢索這個私有屬性還是生成一個新值。 –
@ b3謝謝,我認爲應該這樣做。我想知道爲什麼Matlab在我的實現中進行調用,所以我將把問題留出一段時間。 – MatlabSorter