避免警告“非依赖属性的设置方法不应访问...". [英] Avoid warning "a set method for non-dependent property should not access ..."
问题描述
在一个名为param1, param2
的示例中,我有一个具有某些属性的类,并且有2个相关.它们是独立的,只是受约束的. param2
必须等于或大于param1
,并且必须始终存在(如果param1
确实存在).有问题的代码类似于:
I have a class which has some properties and 2 are related, in the example called param1, param2
. They are independent, just constrained. param2
must be as large or larger than param1
and must always exist if param1
does. Code in question is something like:
function set.param1(obj, input)
disp('setting param1')
obj.param1 = input;
if (isempty(obj.param2) || obj.param2 < obj.param1) % Warning on param2
obj.param2 = obj.param1; % Warning on param2
end
end
set.param2
的类似代码.
代码工作正常,我看不到任何更好的方法.问题-产生警告设置方法...",如标题中所述.由于缺乏更好的解决方案,我压制了它们.
有没有更好的方法来实现此功能并且没有警告?显然,它不是像隐藏功能SetParam2
那样的骇人解决方案":
Similar code for the set.param2
.
Code works fine and I cannot see any better way to do it. The problem - it produces warning "a set method..." like mentioned in title. I suppressed them for the lack of better solution.
Is there a better way to achieve this functionality and without warnings? Obviously not a hacky "solution" like a hidden function SetParam2
:
function SetParam2(obj, input)
obj.param2 = input;
end
这足以使编辑感到困惑,而不会抱怨.
which confuses editor just enough it doesn't complain.
推荐答案
您可以使用两层属性
- 一层暴露在外的
Dependent
- 一层是私有的并且实际存储值
The similar technique is used here in the documentation: Avoid Property Initialization Order Dependency.
classdef TestClass < handle
properties (Access = private)
privateParam1;
privateParam2;
end
properties (Dependent)
param1;
param2;
end
methods
function p1 = get.param1(obj)
p1 = obj.privateParam1;
end
function p2 = get.param2(obj)
p2 = obj.privateParam2;
end
function set.param1(obj, input)
obj.privateParam1 = input;
if (isempty(obj.privateParam2) || obj.privateParam2 < obj.privateParam1)
obj.privateParam2 = obj.param1;
end
end
function set.param2(obj, input)
if (~isempty(obj.privateParam1) && obj.privateParam1 > input)
obj.privateParam2 = obj.privateParam1;
else
obj.privateParam2 = input;
end
end
end
end
此处的窍门:privateParam1
和privateParam2
存储两个值.仅针对公开属性param1
和param2
实现的get和set:get
仅返回内部属性,并且在set
中都可以使用它们而无需分析器警告,因为它们被标记为
The trick here: privateParam1
and privateParam2
stores the two values. The get and set only implemented for the exposed properties param1
and param2
: the get
returns simply the inner property and in the set
both of them can be used without the analyzer warning as they are marked as Dependent
.
这篇关于避免警告“非依赖属性的设置方法不应访问...".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!